Reputation: 507
If an array initialized as:
$arr = array(array(141,151,161),2,3,array(101,102,array(303,404,606,555,789,array(1000,22,9999,array(9057,100000),522))));
Then the result should be: 100000
I have written a function to solve this problem but I need less bytes and less memory of codes.
My Function is:
function MaxArray($arr){
$length = count($arr);
global $maxValue;
for($i=0;$i<$length;$i++){
if(is_int($arr[$i])){
if($maxValue < $arr[$i]){
$maxValue = $arr[$i];
}
}
elseif(is_array($arr[$i])){
MaxArray($arr[$i]);
}
}
return $maxValue;
}
Upvotes: 1
Views: 2163
Reputation: 51950
A handy function for walking over nested arrays is array_walk_recursive()
. It means that you don't have to worry about the handling the recursion yourself and can get on with the task at hand, in this case finding the maximum value.
function MaxArray($arr) {
$max = FALSE;
array_walk_recursive($arr, function ($current) use (&$max) {
if ($max === FALSE) {
$max = $current;
} else {
$max = max($current, $max);
}
});
return $max;
}
Upvotes: 4
Reputation: 19552
Taken from PHP manual but authored by me:
/**
* @param array $array
*
* @return int|null Returns the largest value of the array. Returns NULL if no
* integers are found.
*/
function array_max_recursive(array $array) {
$max = NULL;
$stack = array($array);
do {
$current = array_pop($stack );
foreach ($current as $value) {
if (is_array($value)) {
$stack[] = $value;
} elseif (filter_var($value, FILTER_VALIDATE_INT) !== FALSE) {
// max(NULL, 0) returns NULL, so cast it
$max = (int) max($max, $value);
}
}
} while (!empty($stack));
return $max;
}
Upvotes: 5