I am testing code with lower version v4.3 and v5.3 of PHP, this is bit of code with continue after without semicolon. Its works and give strange output.
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
print "$i
";
}
//Output: 2 its strange
But with echo
throws error Parse error: syntax error, unexpected 'echo' (T_ECHO)
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
echo "$i
";
}
//Output: Parse error: syntax error, unexpected 'echo' (T_ECHO)
The continue
statement accepts a parameter, so you can add more expressions after it:
continue <foo>;
print
is an expression and can be used as part of other statements, so continue print();
is valid syntax. This is also why 2
is being output, the single statement continue print $i;
is being executed when $i == 2
.
echo
is a statement and can not be used as part of other expressions, <anything> echo
is invalid syntax.
pretty sure it's because, in earlier versions of php, you could do
function f(){return 2;}
for($i=0;$i<9;++$i){
for($ii=0;$ii<99;++$ii){
continue f();
}
}
and then it would continue on loop number returned by f() (in this case, the $i loop. if it returned 1, it would continue the $ii loop) in modern versions of PHP, you can hardcode a number, but you can't continue on a variable number anymore, it must be decided at compile time. and print() returns int. echo does not, which is why you get an error, the argument to continue must be an int.
The reason is that the continue statement accepts an optional integer (number of loops to continue), which defaults to 1 if none is given.
By not having a semicolon, PHP will take the next expression to be that integer. The language construct print
returns an integer, so that's fine. However, echo
is a also language construct, but it has no return value. So while the parser is looking for an integer, it bumps into a language construct without a return value, and it gets confused and raises an error.
The real solution is to put in that semicolon, because by not having one you are actually potentially changing the behavior of the continue
.
(In this case you're not, because print always returns one, but in other cases it could actually introduce bugs into your code.)
Reason : Output: 2
because the entire continue print "$i "; is evaluated as a single expression, and so print is called only when $i == 2 is true. (The return value of print is passed to continue as the numeric argument.)