note 78725 deleted from control-structures.switch by crell

From: Date: Wed, 29 Jun 2022 19:42:22 +0000
Subject: note 78725 deleted from control-structures.switch by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218740@lists.php.net to get a copy of this message
Note Submitter: Hayley Watson ---- Something not mentioned in the documentation itself, and only touched on momentarily in these notes, is that the default: case need not be the last clause in the switch. <?php for($i=0; $i<8; ++$i) { echo $i,"\t"; switch($i) { case 1: echo "One"; break; case 2: default: echo "Thingy"; break; case 3: case 4: echo "Three or Four"; break; case 5: echo "Five"; break; } echo "\n"; } ?> Outputs what you'd expect, namely 0 Thingy 1 One 2 Thingy 3 Three or Four 4 Three or Four 5 Five 6 Thingy 7 Thingy with case 2 and the default both producing the same result ("Thingy"); strictly speaking, the case 2 clause is completely empty and control just falls straight through. The same result could have been achieved with <?php switch($i) { case 1: echo "One"; break; case 3: case 4: echo "Three or Four"; break; case 5: echo "Five"; break; default: echo "Thingy"; break; } ?> But if "case 2" represented a fairly common case (other than "everything else"), then it would be better to declare it explicitly, not only because it saves time by not having to test EVERY other case first (in the current example, PHP finds 'case 2' in the first switch in two tests, but in the second switch it has to make four tests before giving up and going with the default) but also because someone (perhaps yourself in a few months' time) will be reading the code and expecting to see it handled. Listing it explicitly aids comprehension

« previous php.notes (#218740) next »