My requirement is to find the greatest/max value in an array, which may contain other arrays within it. For example we could have a look at an array below.
$array =
array(
13,
array(10, 4, 111, 3),
4,
array(23, 450, 12,array(110, 119, 20, 670), 45 ,45,67,89),
);
$max = find_max($array, 0);
print "Maximumum Value is $max";
I already have a working function find_max, but all I wanted to know is what could the best and efficient possible way to do this other than the code given below.
function find_max($array, $maxValue) {
foreach ($array as $member) {
if (is_array($member)) {
$maxValue = find_max($member, $maxValue);
} else {
if($member==$maxValue){
continue;
}
if ($member > $maxValue) {
$maxValue = $member;
}
}
}
return $maxValue;
}
Finding the max value requires O(n), so you can’t improve it drastically, as far as I know.
But, you can add a minor improvement to your code:
output: 670