note 40982 deleted from control-structures.switch by cmb
| From: | cmb@php.net | Date: | Sun, 21 Apr 2019 11:46:39 +0000 |
| Subject: | note 40982 deleted from control-structures.switch by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-210635@lists.php.net to get a copy of this message | ||
Note Submitter: ezekiel at superquenelles dot com
----
In reply to Alex Fung :
The following code doesn't work :
<?php
$x = 18;
$y = 6;
switch ($x) {
case (($y * 4) || (9 * 3)):
echo "Member";
break;
default:
echo "Not a member";
}
?>
Why :
<design at hyperoptix dot com> want to test if $x == $y*4 or $x == 9*3 ($x == (($y*4)||(9*3))
However the case statement evaluate the value of (($y*4)||(9*3)) that is always true because 9*3=27
(!=0)
That's why this code always return true when $x != 0.
The correct code would be :
<?php
$x = 18;
$y = 6;
switch ($x) {
case (($y * 4)):
case ((9*3)):
echo "Member";
break;
default:
echo "Not a member";
}
?>
Boolean logic work inside case statement, you just need to know that the expression in the case
statement is first evaluated then compared with the evaluated value in the switch statement.