Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP short if statement with continue key word and ommit the else part

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:

  1. Can I use continue key word inside short if statement?

  2. 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.

like image 958
Nilesh Avatar asked Aug 10 '18 08:08

Nilesh


1 Answers

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 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.

like image 188
deceze Avatar answered Sep 18 '22 09:09

deceze