tags:

views:

103

answers:

4

Hi,

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 :)

+5  A: 
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().

Tatu Ulmanen
+9  A: 

http://php.net/manual/en/function.min.php

TJMonk15
That would work with arrays, but he's got just plain variables here.
Tatu Ulmanen
@Tatu - actually `min` can take as many arguments as you pass it or an array.
karim79
Thanks, that's solve my problem ! This website is awesome; thanks everybody !!!
Jenson
@Jenson: it's a good idea to accept the answer that solves your problem.
SilentGhost
+6  A: 

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
Yacoby
+2  A: 
$sortedVar = $a < $b ? $a : $b;
Amarghosh