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.
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.
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.
$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);
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With