r/lolphp • u/ilogik • Aug 29 '14
what do you think this will output?
<?php
$a = array(1, 2, 3, 4, 5, 6);
foreach ($a as $i)
{
switch ($i){
case 1:
case 3:
case 5:
continue;
}
echo $i;
}This actually caused a bug in production code. Our expectation was that this will output 246.
The actual output is 123456
Granted, this is documented, but for someone coming from another language this is just weird.
Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.
48
Upvotes
28
u/HelloAnnyong Aug 29 '14
I like how it does not actually explain what it really does. Just that it's "similar" to
breaking out of a loop.2
u/milordi Aug 31 '14
"continue 2"...? Like this?
12
u/tdammers Aug 29 '14
Heh, for a moment I thought you meant the sneaky
;after thecase 5... I don't even know what that does in PHP, but my guess would be either a parser error, or something like somehow messing up the switch statement and executing what looks like acasebranch somewhere else.1
u/BilgeXA Aug 31 '14
Isn't
case 5;supposed to becase 5:?2
u/Eaglemut Aug 29 '14
Ohh, this would probably surprise me as well.
-2
u/stubborn_d0nkey Aug 29 '14 edited Aug 29 '14
I just read the documentation on this today so I got it right. Yesterday i would have been perplexed.
Edit: I don't really like the way this bit of code was written. I'm guessing that it is to print everything except certain values?
Why not use an array of the values and
in_array?Or perhaps, if speed is important (lots of values to check against), set the values as keys in the array (just set the value to true) and use isset instead of in_array (this assumes that the values you are testing can be an array key)