0

I have the following variables:

$a = 100;
$b = 200;
$c = 300;

Now, I'd basically like to be able to check the values of $a, $b and $c and ultimately output something like "$c is 300 and therefore the largest".

How do I achieve this using PHP?

michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

4 Answers4

3

This will work even with negative values:

$a = 100;
$b = 200;
$c = -300;
$max = max($a,$b,$c);
foreach( array('a','b','c') as $v) {
    if ($$v == $max) {
        echo "\$$v is $max and therefore the largest";
        break;
    }
}

output:

$b is 200 and therefore the largest
Toto
  • 89,455
  • 62
  • 89
  • 125
  • +1 Nice ... Probably slightly highjacking the question .. i was trying to answer this and came unstuck on trying to make it as dynamic as possible - is it possible to use the variable `$a` and get its name (ie a) as a string instead of using `array('a','b','c')` ? hope that makes sense ? – Manse Dec 09 '11 at 12:17
  • @ManseUK: Have a look at the doc http://php.net/get_defined_vars , but AFAK it isn't always working http://stackoverflow.com/questions/255312/how-to-get-a-variable-name-as-a-string-in-php – Toto Dec 09 '11 at 12:26
1
$a = 100;
$b = 200;
$c = 300;
$max = "a"
foreach(array("a","b","c") as $v){
if($$v > $$max)$max = $v;
}
echo "$max is $$max";
El'
  • 401
  • 7
  • 19
0

Try This

$arr=array("a"=>100,"b"=>200,"c"=>300);

$val = max($arr);

print_r(array_keys($arr, $val));echo "has maximum value ".$val;
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0
$a = 100;
$b = 200;
$c = 300;

$values = compact( 'a', 'b', 'c' );
arsort( $values );

echo '$' . key( $values ) . ' is ' . current( $values ) . ' and therefore the largest';

I like this solution as it's pretty neat; definitely aesthetically a good solution. Not sure how it would perform against other solutions on a large amount of variables.

I would definitely recommend you try and get the initial values into an array rather than separate variables to begin with.

liquorvicar
  • 6,081
  • 1
  • 16
  • 21