Compare variable more than once, without repeating it

Asked

Viewed 39 times

2

Example:

Have a variable, that may be value between 1 and 10.

I make the comparisons/conditions to print the result.

$var = 5;

if ($var == 1) echo 'A';
else if ($var == 2 || $var == 6) echo 'B';
else if ($var == 3 || $var == 5) echo 'C';
else if ($var == 4) echo 'D';
else echo 'X';

//Saída: C

If I do it this way:

if ($var == 1) echo 'A';
else if ($var == (2 || 6)) echo 'B';
...

At all times will print B.


Doubts:

  • 'Cause you’ll always fall into that condition? ((2 || 6) = 1 = true? In view, yes, the condition is incorrect)
  • There is a form of check several possible values without having to repeat condition 2x or more (($var == 2 || $var == 6))? (type one IN in SQL language)
  • 3

    Type in_array($var, [2, 6])?

  • Exactly what @Andersoncarloswoss said, or if your PHP version is before PHP7: if(in_array($var, array(2,6)) echo 'B';

  • 1

    @Davidalves this syntax has existed since version 5.4 of PHP.

  • Hmm, thanks @Andersoncarloswoss, I thought it had been implemented together with PHP7

  • I just tested it. Running on 5.6!

1 answer

5


It is possible to do what you want using the function in_array

Thus getting PHP5.4 versions+

$var = 5;

if ($var == 1) echo 'A';
else if (in_array($var, [2,6])) echo 'B';
else if (in_array($var, [3,5])) echo 'C';
else if ($var == 4) echo 'D';
else echo 'X';

//Saída: C

Or so in PHP5.3 versions-

$var = 5;

if ($var == 1) echo 'A';
else if (in_array($var, array(2,6))) echo 'B';
else if (in_array($var, array(3,5))) echo 'C';
else if ($var == 4) echo 'D';
else echo 'X';

//Saída: C

Browser other questions tagged

You are not signed in. Login or sign up in order to post.