Compare variable more than once, without repeating it

2

Example:

I have a variable , which can be 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 this:

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

Always will print B .

Questions:

  • Why will you always fall into this condition? ( (2 || 6) = 1 = true? In view, yes, the condition is incorrect)
  • Is there a way to check multiple possible values without having to repeat the condition 2x or more ( ($var == 2 || $var == 6) )? (type IN in SQL language)
asked by anonymous 02.08.2018 / 20:40

1 answer

5

You can do what you want by using the in_array function

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
    
02.08.2018 / 20:50