Reputation: 43
I have 2 variables each containing a number (integer). I would like to sort them to have the lowest number first and the second largest. For example:
$sortedVar = getSmaller(45, 62); // Will return 45
$sortedVar = getSmaller(87, 23); // Will return 23
Do you see what I want to do? Can you help me please? Thanks :)
Upvotes: 1
Views: 2103
Reputation: 4079
http://php.net/manual/en/function.min.php
min — Find lowest value..
If the first and only parameter is an array,
min()
returns the lowest value in that array. If at least two parameters are provided,min()
returns the smallest of these values.Note: Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an integer as though it were 0, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.
Caution Be careful when passing arguments with mixed types values because
min()
can produce unpredictable results...
Upvotes: 10
Reputation: 55465
Use min() which supports any number of arguments as well as arrays.
$smallest = min(1,2); //returns 1
$smallest = min(4,3,2); //returns 2
$smallest = min(array(5,4)) //returns 4
Upvotes: 8
Reputation: 124838
function getSmaller($a, $b) {
return $a < $b ? $a : $b;
}
In plain english, if $a is smaller than $b, then return $a, else return $b.
Or as others pointed out, there's also a function for that, called min().
Upvotes: 5