PHP中是否有三元操作员的向后版?
如果条件为true,我将尝试为一个数组分配一些值,否则我想将其分配给另一个数组。我知道这是有可能的。但是,我想知道是否可以使用三元操作员的语法来完成?
但是,使用IF语句看起来像这样
if(condition){
$foo[] = $value;
} else{
$bar[] = $value;
}
,我的问题是是否可以写与此相似?
((condition) ? ($foo[]) : ($bar[])) = $value;
I am trying to assign some value to one array if a condition is true otherwise I want to assign it to another array. I know this is possible with an if statement. However, I am wondering if it can be done with the syntax of a ternary operator?
Using an if statement it would look like this
if(condition){
$foo[] = $value;
} else{
$bar[] = $value;
}
However, my question is if it is possible to write it similar to this?
((condition) ? ($foo[]) : ($bar[])) = $value;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您可以与您想要的方式略有不同,如下:
第一种方法是在每个三元块中分配值。
在线demo
第二种方法是使用
array_push
如下:在线演示
注意:用您的条件替换
true
。Yes you can but slightly different from the way you desire, like below:
First way is to assign value in each of the ternary blocks.
Online Demo
Second way is to use
array_push
like below:Online Demo
Note: Replace the
true
with your condition.这样的语句只会导致语法错误或致命错误:
您也可以尝试引用该错误,但仍然无法使用:
IF语句可能是您的最佳选择。但是,如果您真的想做这样的事情,则可以将单个关联数组与
foo
和bar
只是密钥:A statement like this will only result in a syntax error, or a fatal error:
You could also try to reference the but it still won't work:
The if statement is probably your best option. However if you really want to do something like this, you could use a single associative array with
foo
andbar
just being keys:尝试一下。
条件? ($ foo [] = $ value):($ bar [] = $ value);
Try this.
condition ? ($foo[] = $value) : ($bar[] = $value);