Checking Multidimensional Arrays in PHP

Web-hosting business can now be started for just $19.95 with unlimited resources. Start your own.

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 way, what you want to check is, is 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 Way

  1. function is_multi_array( $arr ) {    //Buggy
  2.     return (count($arr)!==count($arr,COUNT_RECURSIVE));
  3. }
PHP Code
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 Way

  1. function is_multi_array( $arr ) {
  2.     rsort( $arr );
  3.     return isset( $arr[0] ) && is_array( $arr[0] );
  4. }
  5.  
  6. //Usage
  7. var_dump( is_multi_array( $some_array ) );
PHP Code
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.



  1. High Performance Hosting is now $3.96 a month


© 2012-2017 PageConfig.com - Scripts - Twitter