I have a for loop like
for ($x=1; $x<=5; $x++){
($x == 3)? continue : true;
//some code here
}
now on execution I am getting error
PHP Parse error: syntax error, unexpected 'continue' (T_CONTINUE) in /var/www/html/all.php on line 21
Now, this leave me with 2 questions:
Can I use continue key word inside short if statement?
For the else part of the short if, can binary values like true or false be used, and if not then how can I use short if statement if I have nothing to do for the else part.
continue
is a statement (like for
, or if
) and must appear standalone. It cannot be used as part of an expression . Partly because continue
doesn't return a value , but in an expression every sub-expression must result in some value so the overall expression results in a value. That's the difference between a statement and an expression.
cond ? a : b
cond ? a : b
means use value a
if cond
is true else use value b
. If a
is continue
, there's no value there.
true
does result in a value ( true
), so yes, it can be used as part of an expression.
You cannot use continue
inside short if-statement. Short if-statements is for returning values, like this
$val = $bool ? $one : $two;
Now, $val
will have either the value of $one
or the value of $two
, depending of the truth value of $bool
.
continue
is no value, so it cannot be used in short if-statement. Use normal if-statement for this operation.
In this case, I would have done it like this:
for ($x=1; $x<=5; $x++){
if($x == 3) continue;
//some code here
}
You can use continue key word inside if statement like this; (according to PHP documentation)
<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
print "$i\n";
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.