note 68408 added to control-structures.switch

From: Date: Tue, 25 Jul 2006 22:43:02 +0000
Subject: note 68408 added to control-structures.switch
Groups: php.notes 
Request: Send a blank email to php-notes+get-115192@lists.php.net to get a copy of this message
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! ---- Server IP: 66.163.161.117 Probable Submitter: 169.237.7.55 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/control-structures.switch.php Edit -- http://master.php.net/note/edit/68408 Del: integrated -- http://master.php.net/note/delete/68408/integrated Del: useless -- http://master.php.net/note/delete/68408/useless Del: bad code -- http://master.php.net/note/delete/68408/bad+code Del: spam -- http://master.php.net/note/delete/68408/spam Del: non-english -- http://master.php.net/note/delete/68408/non-english Del: in docs -- http://master.php.net/note/delete/68408/in+docs Del: other reasons-- http://master.php.net/note/delete/68408 Reject -- http://master.php.net/note/reject/68408 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#115192) next »