Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to find out how "deep" a PHP array is?

A PHP array can have arrays for its elements. And those arrays can have arrays and so on and so forth. Is there a way to find out the maximum nesting that exists in a PHP array? An example would be a function that returns 1 if the initial array does not have arrays as elements, 2 if at least one element is an array, and so on.

like image 443
Thomas Owens Avatar asked Nov 04 '08 18:11

Thomas Owens


People also ask

How do you find the size of an array in PHP?

How to Count all Elements or Values in an Array in PHP. We can use the PHP count() or sizeof() function to get the particular number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that we can initialize with an empty array.

What is the depth of an array?

In the flat array model, the depth is the number of levels of boxing in an array. More precisely, the depth of a non-boxed or empty array is 0, and a non-empty boxed array has depth equal to one plus the maximum of the depths of the arrays it contains.

How do you find the maximum and minimum of an array in PHP?

$min = min($numbers); $max = max($numbers); Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map : $numbers = array_map(function($details) { return $details['Weight']; }, $array);

How do I scan an array in PHP?

You can use array_walk_recursive() function for "scan" the arrays. This function will recurse into deeper arrays. You will get back every member of an array.


1 Answers

Here's another alternative that avoids the problem Kent Fredric pointed out. It gives print_r() the task of checking for infinite recursion (which it does well) and uses the indentation in the output to find the depth of the array.

function array_depth($array) {     $max_indentation = 1;      $array_str = print_r($array, true);     $lines = explode("\n", $array_str);      foreach ($lines as $line) {         $indentation = (strlen($line) - strlen(ltrim($line))) / 4;          if ($indentation > $max_indentation) {             $max_indentation = $indentation;         }     }      return ceil(($max_indentation - 1) / 2) + 1; } 
like image 144
Paige Ruten Avatar answered Sep 21 '22 15:09

Paige Ruten