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.
To find the largest element, use max( ):
$largest = max($array);
To find the smallest element, use min( ):
$smallest = min($array);
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( ).
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.
Copyright © 2003 O'Reilly & Associates. All rights reserved.