This is my code:
$array = [1,2,3];
foreach($array as $n){
switch($n){
case 1:
print 1;
case 2:
print 2;
default:
print 3;
}
}
It prints 123233
I don't get it, shouldn't it print 123 ?? I'm confused because:
Why isn't it working as expected?
Add break
after any print.
$array = [1,2,3];
foreach($array as $n){
switch($n){
case 1:
print 1;
break;
case 2:
print 2;
break;
default:
print 3;
break;
}
}
If you wouldn't had a break
keyword, then the code would be continue to be executed from the point of the case.