4.15. Finding the Largest or Smallest Valued Element in an Array4.15.1. ProblemYou 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. 4.15.2. SolutionTo find the largest element, use max( ): $largest = max($array); To find the smallest element, use min( ): $smallest = min($array); 4.15.3. DiscussionNormally, 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( ). 4.15.4. See AlsoRecipe 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. |
|