note 78725 added to control-structures.switch
| From: | HayleyWatson at osu1 dot php dot net | Date: | Wed, 24 Oct 2007 21:02:20 +0000 |
| Subject: | note 78725 added to control-structures.switch | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-131707@lists.php.net to get a copy of this message | ||
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
----
Server IP: 203.89.181.186
Probable Submitter: 60.234.168.92
----
Manual Page -- http://www.php.net/manual/en/control-structures.switch.php
Edit -- https://master.php.net/note/edit/78725
Del: integrated -- https://master.php.net/note/delete/78725/integrated
Del: useless -- https://master.php.net/note/delete/78725/useless
Del: bad code -- https://master.php.net/note/delete/78725/bad+code
Del: spam -- https://master.php.net/note/delete/78725/spam
Del: non-english -- https://master.php.net/note/delete/78725/non-english
Del: in docs -- https://master.php.net/note/delete/78725/in+docs
Del: other reasons-- https://master.php.net/note/delete/78725
Reject -- https://master.php.net/note/reject/78725
Search -- https://master.php.net/manage/user-notes.php