Hướng dẫn check is array php

[PHP 4, PHP 5, PHP 7, PHP 8]

is_arrayFinds whether a variable is an array

Description

is_array[mixed $value]: bool

Parameters

value

The variable being evaluated.

Return Values

Returns true if value is an array, false otherwise.

Examples

Example #1 Check that variable is an array

The above example will output:

See Also

  • array_is_list[] - Checks whether a given array is a list
  • is_float[] - Finds whether the type of a variable is float
  • is_int[] - Find whether the type of a variable is integer
  • is_string[] - Find whether the type of a variable is string
  • is_object[] - Finds whether a variable is an object

Rob Thomas

5 years ago

Please note that the 'cast to array' check is horrendously out of date.

Running that code against PHP 5.6 results in this:

is_array  :  0.93975400924683
cast, === :  1.2425191402435

So, please use 'is_array', not the horrible casting hack.

ari at umbrella dot bz

6 years ago

hperrin's results have indeed changed in PHP 7. The opposite is now true, is_array is faster than comparison:

is_array  :  0.52148389816284
cast, === :  0.84179711341858

Tested 1000000 iterations.

skaimauve at yahoo dot ca

13 years ago

Or you could make use of the array_diff_key and array_key function:



In my tests it runs about twice as fast as Michael/Gabriel's array_reduce[] method.

[Speaking of which: Gabriel's version doesn't work as written; it reports associative arrays as numeric if only the first key is non-numeric, or if the keys are numeric but ordered backwards.  Michael solves this problem by comparing array_reduce[] to count[], but that costs another function call; it also works to just compare to -1 instead of 0, and therefore return -1 as the ternary else from the callback].

hperrin at gmail dot com

12 years ago

I've found a faster way of determining an array. If you use is_array[] millions of times, you will notice a *huge* difference. On my machine, this method takes about 1/4 the time of using is_array[].

Cast the value to an array, then check [using ===] if it is identical to the original.



You can use this script to test the speed of both methods.


What's faster for determining arrays?

Chủ Đề