Forked from thcipriani/continue-switch-in-loop-weirdness.php
Created
November 8, 2017 11:00
-
-
Save otengkwame/83d47ebb3cecd8f47f9e5942dfb82268 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$arr = array(1, 2, 3); | |
/** | |
* PHP Weirdness 1 | |
* 'continue' acts like 'break' inside of a switch statement when inside of a loop | |
* whereas 'continue' acts as expected inside an elseif block | |
*/ | |
foreach ($arr as $item) { | |
switch($item) { | |
case 1: | |
echo 'one'; | |
break; | |
case 2: | |
echo 'two'; | |
continue; | |
case 3: | |
echo 'three'; | |
break; | |
} | |
echo ' wasn\'t skipped' . PHP_EOL; | |
} | |
/** | |
* OUTPUT: | |
* one wasn't skipped | |
* two wasn't skipped | |
* three wasn't skipped | |
*/ | |
// -------- VS. ---------- // | |
foreach ($arr as $item) { | |
if ($item == 1) { | |
echo 'one'; | |
} elseif ($item == 2) { | |
echo 'two'; | |
continue; | |
} elseif ($item == 3) { | |
echo 'three'; | |
} | |
echo ' wasn\'t skipped' . PHP_EOL; | |
} | |
/** | |
* OUTPUT: | |
* one wasn't skipped | |
* twothree wasn't skipped | |
*/ | |
// -------- FIX! ---------- // | |
foreach ($arr as $item) { | |
switch($item) { | |
case 1: | |
echo 'one'; | |
break; | |
case 2: | |
echo 'two'; | |
continue 2; | |
case 3: | |
echo 'three'; | |
break; | |
} | |
echo ' wasn\'t skipped' . PHP_EOL; | |
} | |
/** | |
* end Weirdness 1 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment