note 68408 deleted from control-structures.switch by nlopess

From: Date: Thu, 27 Jul 2006 15:55:03 +0000
Subject: note 68408 deleted from control-structures.switch by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-115277@lists.php.net to get a copy of this message
Note Submitter: Gary ---- I was toying with the switch construct and found that its semantics are somewhat surprising. Not only can expressions with side effects be used as the case expressions (and those expressions will be executed in sequence until a matching one is found), but it would seem that the switch expression itself gets re-evaluated on each comparison. If this is correct, then it does not seem that switch would be any faster than if-else's. Consider the following example: <?php $i = 10; switch ($i) { case (3) : echo "i is 3"; break; case ($i = 5) : echo "i = " . $i; break; case (10) : echo "i is still 10"; } echo "\n" . "After the switch, i = " . $i; ?> This code fragment will output: i = 5 After the switch, i = 5 The first evaluation of ($i) returns 10, and the expression ($i = 5) returns the value 5. Given that the line "i = 5" gets echoed, it would seem that the switch expression, ($i), is re-evaluated after the case expression is evaluated. I find this quite counter-intuitive and rather disturbing. If anyone knows the evaluation proceeds otherwise than I have explained it, please let us all know!

« previous php.notes (#115277) next »