Find the maximum value in an array

My requirement is to find the largest / maximum value in the array, which may contain other arrays inside it. For example, we could take a look at the 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 find_max working function, but all I wanted to know was that there might be a better and more efficient way to do it differently than the code 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; } 
+4
source share
3 answers

O (n) is required to determine the maximum value, so you cannot improve it as far as I know. But you can add a slight improvement to your code:

 function find_max($array, $maxValue) { foreach ($array as $member) { if (is_array($member)) { $maxValue = find_max($member, $maxValue); } else { if ($member > $maxValue) { $maxValue = $member; } } } return $maxValue; } $array = array( 13, array(10, 4, 111, 3), 4, array(23, 450, 12,array(110, 119, 20, 670), 45 ,45,67,89), ); $ans = find_max($array, 0); echo "ans = $ans"; 

output: 670

+1
source

You cannot find the maximum array (or array of arrays) faster than O (n) or linear time .

If you need to constantly find the maximum of this array, I would recommend sorting the array or using a different (sorted) data structure, if possible.

You can also save the link to max and update it when inserting data. Obviously, this assumes that you insert the data yourself, and not get it from another place, in which case my last comment is useless to you.

+2
source

Indeed, what you are doing would be the best way to search for max in a multidimensional array. Using recursion to find depth and check for a larger number. Unfortunately, there is no built-in function for this.

This is a complicated way to sort a multidimensional array based on the innermost array, but it is a rather complicated concept. (looking for him).

can usort be useful?

+1
source

All Articles