I have following array:
$ar3 = array(123, array(12, 665, array(77, 255, 98, 56), 8), 1155, 676);
I need to compare all of its elements with
PHP already offers a native recursive function to traverse all leaf nodes of a multidimensional array called array_walk_recursive(). This offers a clean, concise, intuitive line of code. When future developers look at your code, they will know immediately what your line of code is trying to achieve without following multiple lines of code and logic. This will enable better maintainability and show that you know a direct tool for the task at hand.
After establishing a base or default value for $max
, you write a user-defined function (or "closure") that handles the conditional logic. The fiddly thing about closures is that they have their own "scope" -- this means that the variables within are not available outside of the function (at least, not without help). global
declarations are generally inadvisable (in many cases a bad habit, and the line will be read on each iteration) even though they are well-intentioned, so use()
will serve as the means to import the variable and &
(which makes the variable "modifiable by reference") will serve as a means to export the variable from function scope back to the global scope.
Code: (Demo)
$ar3 = array(123, array(12, 665, array(77, 255, 98, 56), 8), 1155, 676);
$max = null; // declare a non-integer or minimum value here
array_walk_recursive($ar3, function($v)use(&$max){if($max === null || $v > $max) $max = $v;});
echo $max; // output: 1155
*array_walk_recursive()
returns true
or false
. You cannot use return
inside the closure to move $max
to the global scope.
*If you are going to initially declare $max
as 0
(because you don't expect negative values), then you won't need the $max === null
check in your conditional expression.
*If you are processing excessively deep multi-dimensional arrays (like hundreds of levels), then it is possible that a stack crash could occur. I tried to find a reference for this claim, but I can't find a link anywhere -- I did read it somewhere though.