PHP中是否有三元操作员的向后版?

发布于 2025-02-04 06:23:53 字数 340 浏览 2 评论 0原文

如果条件为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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

宣告ˉ结束 2025-02-11 06:23:53

是的,您可以与您想要的方式略有不同,如下:

  • 第一种方法是在每个三元块中分配值。

     是吗? ($ foo [] = $ value):($ bar [] = $ value);
     

在线demo

  • 第二种方法是使用 array_push 如下:

      array_push($ {true?'foo':'bar'},$ value);
     

在线演示

注意:用您的条件替换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.

    true ? ($foo[] = $value) : ($bar[] = $value);
    

Online Demo

  • Second way is to use array_push like below:

    array_push(${ true ? 'foo' : 'bar' }, $value);
    

Online Demo

Note: Replace the true with your condition.

妳是的陽光 2025-02-11 06:23:53

这样的语句只会导致语法错误或致命错误:

(true ? $foo : $bar)[] = 42;
// Fatal error: Cannot use temporary expression in write contex

您也可以尝试引用该错误,但仍然无法使用:

$arr = true ? &$foo : &$bar;
$arr[] = 42;
// Parse error: syntax error, unexpected token "&"

IF语句可能是您的最佳选择。但是,如果您真的想做这样的事情,则可以将单个关联数组与foobar只是密钥:

$arr = [
    'foo' => [],
    'bar' => [],
];

$arr[true ? 'foo' : 'bar'][] = 42;

A statement like this will only result in a syntax error, or a fatal error:

(true ? $foo : $bar)[] = 42;
// Fatal error: Cannot use temporary expression in write contex

You could also try to reference the but it still won't work:

$arr = true ? &$foo : &$bar;
$arr[] = 42;
// Parse error: syntax error, unexpected token "&"

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 and bar just being keys:

$arr = [
    'foo' => [],
    'bar' => [],
];

$arr[true ? 'foo' : 'bar'][] = 42;
感性不性感 2025-02-11 06:23:53

尝试一下。

条件? ($ foo [] = $ value):($ bar [] = $ value);

Try this.

condition ? ($foo[] = $value) : ($bar[] = $value);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文