0

I have a variable that I need to check against other variables to make sure it is greater than them. I've simplified the example below, but here's a working example of the desired result.

<?php
  $a = 5;
  $b = 4;
  $c = 3;
  $d = 2;
  $e = 1;

  if(($a > $b) && ($a > $c) && ($a > $d) && ($a > $e)){
    echo "A is the biggest";
  }else{
    echo "A is not the biggest";
  }
?>

My question is, is there a simpler way to write the if statement so that we don't have to have $a written four separate times? Something along the lines of ...

if($a > $b,$c,$d,$e){

I've seen Simpler way to check if variable is not equal to multiple string values? but this is for checking the presence of strings.

John
  • 27
  • 4
  • `if($a == max($a,$b,$c,$d,$e)){` would work, check out [php's max function](http://php.net/manual/en/function.max.php). – Keyur PATEL Feb 12 '18 at 03:39

2 Answers2

1

Just like you can have an array of strings, you can have an array of variables.

The 'most simplistic' approach would be to return the max() of the array variables, and then simply check whether $a is greater than that. This way you only have to do one comparison.

if (($a > $b) && ($a > $c) && ($a > $d) && ($a > $e)) { }

Can be re-written as:

$values = array($b, $c, $d, $e); // array(4, 3, 2, 1);
if ($a > max($values)) { } // if (5 > 4) { }

Hope this helps!

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

I'd write something like that:

if (max($a, $b, $c, $d, $e) == $a) {
    ....
}
Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57