4.14. Finding the Largest or Smallest Valued Element in an Array
Problem
You have an array of elements, and you want to find the largest or smallest valued element. For example, you want to find the appropriate scale when creating a histogram.
Solution
To find the largest element, use max( )
:
$largest = max($array);
To find the smallest element, use min( )
:
$smallest = min($array);
Discussion
Normally, max( ) returns the larger of two
elements, but if you pass it an array, it searches the entire array
instead. Unfortunately, there’s no way to find the
index of the largest element using max( ).
To do that,
you must sort the array in reverse order to put the largest element
in position 0:
arsort($array);
Now the value of the largest element is $array[0].
If you don’t want to disturb the order of the original array, make a copy and sort the copy:
$copy = $array; arsort($copy);
The same concept applies to min( ) but use
asort( )
instead of arsort( ).
See Also
Recipe 4.17 for sorting an array;
documentation on max( ) at
http://www.php.net/max, min( ) at http://www.php.net/min,
arsort( ) at
http://www.php.net/arsort, and asort( ) at http://www.php.net/min.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access