[英]PHP short if statement with continue key word and ommit the else part
I have a for loop like 我有一个for循环
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
PHP解析错误:语法错误,第21行/var/www/html/all.php中的意外“继续”(T_CONTINUE)
Now, this leave me with 2 questions: 现在,这给我留下两个问题:
Can I use continue key word inside short if statement? 我可以在short if语句中使用continue key word吗?
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. 对于short if的else部分,可以使用像true或false这样的二进制值,如果没有,那么如果我对else部分无关,我怎么能使用short if语句。
continue
is a statement (like for
, or if
) and must appear standalone. continue
是一个声明 (如for
或if
),必须单独出现。 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. 部分原因是
continue
不返回值 ,但在表达式中,每个子表达式都必须产生一些值,因此整个表达式会产生一个值。 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
. cond ? a : b
表示使用值a
如果cond
为真,则使用值b
。 If a
is continue
, there's no value there. 如果
a
continue
,那里没有价值。
true
does result in a value ( true
), so yes, it can be used as part of an expression. true
会导致值( true
),所以是的,它可以用作表达式的一部分。
You cannot use continue
inside short if-statement. 你不能在short if语句中使用
continue
。 Short if-statements is for returning values, like this 简短的if语句用于返回值,就像这样
$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
. 现在,
$val
将具有$one
的值或$two
的值,具体取决于$bool
的真值。
continue
is no value, so it cannot be used in short if-statement. continue
是没有价值的,所以它不能用于简短的if语句。 Use normal if-statement for this operation. 对此操作使用普通的if语句。
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; 你可以在if语句中使用continue key word; (according to PHP documentation)
(根据PHP文档)
<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
print "$i\n";
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.