Home > Mobile >  Is there a backwards version of a ternary operator in php?
Is there a backwards version of a ternary operator in php?

Time:06-04

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;

CodePudding user response:

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.

CodePudding user response:

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;

CodePudding user response:

Try this.

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

  • Related