skip to Main Content

I have code that looks like this:

$foo = false;

$ar = ["bar", "baz"];

if ($foo === true)  {
    $ar[] = "corge";
}

 
var_dump($ar);

so if $foo is true, $ar should look like this: ["bar", "baz", "corge"], otherwise it should look like this: ["bar", "baz"].

Is there a shorthand operator in php that will allows me to eliminate that if?

solutions like ternary, null coalesce and Elvis all create a third element when $foo is false.

3

Answers


  1. It’s much less clear in its intent, but it’s certainly possible to write it like this:

    $foo === false or $ar[] = "corge";
    

    Live demo: https://3v4l.org/5XHeb

    Login or Signup to reply.
  2. You can use a ternary along with array_merge(). Merge with an empty array to avoid pushing anything.

    $ar = array_merge($ar, $foo ? ["corge"] : []);
    
    Login or Signup to reply.
  3. To have another option you could use a ternary operator.

    $foo ? $ar[] = "corge" : null;
    

    If $foo is true, corge will be added, else nothing happens. Instead of null you could use any other value, because it has no effect.

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