Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a backwards version of a ternary operator in php?

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;
like image 451
Michael Grinnell Avatar asked Dec 06 '25 16:12

Michael Grinnell


1 Answers

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.

like image 55
nice_dev Avatar answered Dec 08 '25 21:12

nice_dev