note 109034 added to control-structures.switch

From: Date: Thu, 14 Jun 2012 14:29:31 +0000
Subject: note 109034 added to control-structures.switch
Groups: php.notes 
Request: Send a blank email to php-notes+get-188602@lists.php.net to get a copy of this message
This is listed in the documentation above, but it's a bit tucked away between the paragraphs. The difference between a series of if statements and the switch statement is that the expression you're comparing with, is evaluated only once in a switch statement. I think this fact needs a little bit more attention, so here's an example: <?php $a = 0; if(++$a == 3) echo 3; elseif(++$a == 2) echo 2; elseif(++$a == 1) echo 1; else echo "No match!"; // Outputs: 2 $a = 0; switch(++$a) { case 3: echo 3; break; case 2: echo 2; break; case 1: echo 1; break; default: echo "No match!"; break; } // Outputs: 1 ?> It is therefore perfectly safe to do: <?php switch(winNobelPrizeStartingFromBirth()) { case "peace": echo "You won the Nobel Peace Prize!"; break; case "physics": echo "You won the Nobel Prize in Physics!"; break; case "chemistry": echo "You won the Nobel Prize in Chemistry!"; break; case "medicine": echo "You won the Nobel Prize in Medicine!"; break; case "literature": echo "You won the Nobel Prize in Literature!"; break; default: echo "You bought a rusty iron medal from a shady guy who insists it's a Nobel Prize..."; break; } ?> without having to worry about the function being re-evaluated for every case. There's no need to preemptively save the result in a variable either. ---- Server IP: 83.137.20.135 Probable Submitter: 87.195.224.218 ---- Manual Page -- http://www.php.net/manual/en/control-structures.switch.php Edit -- https://master.php.net/note/edit/109034 Del: integrated -- https://master.php.net/note/delete/109034/integrated Del: useless -- https://master.php.net/note/delete/109034/useless Del: bad code -- https://master.php.net/note/delete/109034/bad+code Del: spam -- https://master.php.net/note/delete/109034/spam Del: non-english -- https://master.php.net/note/delete/109034/non-english Del: in docs -- https://master.php.net/note/delete/109034/in+docs Del: other reasons-- https://master.php.net/note/delete/109034 Reject -- https://master.php.net/note/reject/109034 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#188602) next »