note 101465 deleted from control-structures.switch by danbrown
| From: | danbrown@php.net | Date: | Sat, 18 Dec 2010 18:33:55 +0000 |
| Subject: | note 101465 deleted from control-structures.switch by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-175045@lists.php.net to get a copy of this message | ||
Note Submitter: cory at watchdogserver dot com
----
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