When working with arrays in PHP, you may often need to check whether each of an array’s element contains scalar data or is there an element that contains another array (a sub-array). In other words, what you want is to check if the array multidimensional? To solve the mystery, many people quote a buggy snippet on stackoverflow and other programming websites. Reading through such pages, I decided to explain a bug in the most commonly used method of checking multidimensional arrays, and also to provide the right solution.
The Wrong Method
function is_multi_array( $arr ) { //Buggy return (count($arr)!==count($arr,COUNT_RECURSIVE)); }
The logic behind this solution is that the count($arr)
counts elements at just the first level in the array while the count
with COUNT_RECURSIVE
goes deeper and counts all elements in the array at all levels. For a multidimensional array, it is obvious that results of these two will not be the same, and a comparison of their return values gives us the answer. If both counts are same, the passed array is a flat one, otherwise it is a multidimensional array and the function would return true
. But this is incorrect.
If we have an empty array inside another array, both normal count and COUNT_RECURSIVE
return the same count of elements and this function will return false
even if the array is multidimensional.
The Correct Method
function is_multi_array( $arr ) { rsort( $arr ); return isset( $arr[0] ) && is_array( $arr[0] ); } //Usage var_dump( is_multi_array( $some_array ) );
rsort
sorts all the sub-arrays towards the beginning of the parent array, and re-indexes the array. This ensures that if there are one or more sub-arrays inside the parent array, the first element of parent array (at index 0
) will always be an array. Checking for the element at index 0
, we can tell whether the array is multidimensional or not.