Finding the Lowest or Highest Number with PHPWritten by Mark Sanborn: May 16, 2008
Recently I was writing a script and ran into a problem. I needed to compare a set of numbers and find the lowest one. Now, at first I thought that I could compare each one with if statements but I knew there had to be a better way (there always is). If you have 1000 numbers you would never be able to write all that code to work efficiently.
Fortunately PHP provides the two functions that I needed. One function for finding the lowest number in a dataset and one function to find the highest.
Finding the Lowest Number
echo min(2, 3, 1, 6, 7); // PHP would print '1'.
You can also determine the lowest number in an array:
Finding the Highest Number
As you may have guessed we will use the opposite of min, Max.
echo max(2, 3, 1, 6, 7); // PHP would print '7'.
A Practical Example
I mentioned that I need to find the lowest number in a data set in one of my scripts. The script was a rate comparison tool that utilized two functions that I created for querying rates from both UPS and The US Postal Service. I wanted to simply highlight the lowest rate. I utilized PHP’s min function as I briefly described above.
<?php lowestRate = min($UPSGroundRate,$USPSPriorityRate,$USPSParcelRate,$USPSFlatRate); ?>
Need to print shipping labels on your site?
Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.