PHP Arrays Finding the Largest or Smallest Valued Element in an Array - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Arrays Finding the Largest or Smallest Valued Element in an Array - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Sunday, May 19, 2019

PHP Arrays Finding the Largest or Smallest Valued Element in an Array

PHP Arrays



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 uses asort() instead of arsort().

Both max() and min() issue a warning if you provide them with an empty array.


No comments:

Post a Comment

Post Top Ad