note 40982 modified in control-structures.switch by vrana
| From: | vrana@php.net | Date: | Tue, 17 Aug 2004 13:54:17 +0000 |
| Subject: | note 40982 modified in control-structures.switch by vrana | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-80063@lists.php.net to get a copy of this message | ||
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.
--was--
In reply to Alex Fung :
The following code doesn't work :
$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 :
$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.
http://php.net/manual/en/control-structures.switch.php