PHP Continue - removed support for variable numeric argument (e.g. continue $num)

373 Views Asked by At

http://php.net/manual/en/control-structures.continue.php

Changelog says that as of 5.4, following change happened: Removed the ability to pass in variables (e.g., $num = 2; continue $num;) as the numerical argument.

Why on earth would they do that?

So, basically, this is now invalid:

for ($i = 0; $i < 10; $i++) {
    $num = 5;
    continue $num;
}

Am I understanding this correctly? Why would they do that? I just cannot think of a reason.

2

There are 2 best solutions below

4
On BEST ANSWER
$i = 0;
while ($i++ < 5) {
    echo "Outer<br />\n";
    while (1) {
        echo "Middle<br />\n";
        while (1) {
            echo "Inner<br />\n";
            continue 3;
        }
        echo "This never gets output.<br />\n";
    }
    echo "Neither does this.<br />\n";
}

here in the above example from PHP Manual the continue skips the echo "This never gets output.<br />\n"; and echo "Neither does this.<br />\n"; statement and the continue 3; denotes the loop number to continue

for ($i = 0; $i < 10; $i++) {
    $num = 5;
    continue ;
    echo $num;
}

the above will skip the printing of $num

0
On

Searching for an alternative function or similar for being able to pass a dynamic variable to continue; and the accepted answer is nowhere related with the question,

I found a workaround that works instead:

$totalLoops = 20;
$skipLoops = 5;
$cnt = 0;
while ($cnt < $totalLoops){
    ++$cnt;  
    if ($cnt <= $skipLoops){continue;}
    echo "Next number is: $cnt<br>";
}

Change the $skipLoops to how many loops you want to skip and you have an alternative of dynamic continue.