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 oneIN
in SQL language)
Type
in_array($var, [2, 6])
?– Woss
Exactly what @Andersoncarloswoss said, or if your PHP version is before PHP7:
if(in_array($var, array(2,6)) echo 'B';
– David Alves
@Davidalves this syntax has existed since version 5.4 of PHP.
– Woss
Hmm, thanks @Andersoncarloswoss, I thought it had been implemented together with PHP7
– David Alves
I just tested it. Running on 5.6!
– rbz