skip to Main Content

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;

3

Answers


  1. 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;
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. Try this.

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search