note 101465 added to control-structures.switch
| From: | cory at watchdogserver dot com | Date: | Sat, 18 Dec 2010 06:42:59 +0000 |
| Subject: | note 101465 added to control-structures.switch | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-175037@lists.php.net to get a copy of this message | ||
Somewhere above, this example below was shown and said to be an error within PHP where more than one
default would trigger.
<?php
switch(9) {
case 1:
echo 1 . "\n";
case 2:
echo 2 . "\n";
break;
case 3:
echo 3 . "\n";
case 4:
echo 4 . "\n";
case 5:
echo 5 . "\n";
default:
echo 6 . "\n";
default:
echo 7 . "\n";
default:
echo 8 . "\n";
}
// Outputs:
// 8
//
// Did you expect 6 and 7 to print too?
switch(3) {
case 1:
echo 1 . "\n";
case 2:
echo 2 . "\n";
break;
case 3:
echo 3 . "\n";
case 4:
echo 4 . "\n";
case 5:
echo 5 . "\n";
default:
echo 6 . "\n";
default:
echo 7 . "\n";
default:
echo 8 . "\n";
}
// Outputs:
// 3
// 4
// 5
// 6
// 7
// 8
?>
CORRECTION:
The reason it outputs 8 on the first example is because the last default listed is triggered. Yes,
this part is correct. However the reason the second example outputs 3 4 5 6 7 8 is not because of an
error within PHP rather an error in your code. It is triggering all of the cases simply because you
did not place a break after each case. Call it a "run-on-case" or lack of break/stop point
definition.
Second example re-written: (Correctly)
<?php
switch(3) {
case 1:
echo 1 . "\n";
break;
case 2:
echo 2 . "\n";
break;
case 3:
echo 3 . "\n";
break;
case 4:
echo 4 . "\n";
break;
case 5:
echo 5 . "\n";
break;
default:
echo 6 . "\n";
break;
default:
echo 7 . "\n";
break;
default:
echo 8 . "\n";
break;
}
?>
// outputs
// 3
I think the point you were trying to make is with more than one default listed only the last default
is triggered. This is correct. The rest is simply a mistake in coding.
Now, whether should PHP allow/permit run-on-cases to occur could be considered an error within php,
yes, but not the error as you have described.
Tested with PHP 5.3.4
----
Server IP: 208.69.120.55
Probable Submitter: 70.126.104.89
----
Manual Page -- http://www.php.net/manual/en/control-structures.switch.php
Edit -- https://master.php.net/note/edit/101465
Del: integrated -- https://master.php.net/note/delete/101465/integrated
Del: useless -- https://master.php.net/note/delete/101465/useless
Del: bad code -- https://master.php.net/note/delete/101465/bad+code
Del: spam -- https://master.php.net/note/delete/101465/spam
Del: non-english -- https://master.php.net/note/delete/101465/non-english
Del: in docs -- https://master.php.net/note/delete/101465/in+docs
Del: other reasons-- https://master.php.net/note/delete/101465
Reject -- https://master.php.net/note/reject/101465
Search -- https://master.php.net/manage/user-notes.php