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
It’s much less clear in its intent, but it’s certainly possible to write it like this:
Live demo: https://3v4l.org/5XHeb
You can use a ternary along with
array_merge()
. Merge with an empty array to avoid pushing anything.To have another option you could use a ternary operator.
If
$foo
istrue
,corge
will be added, else nothing happens. Instead ofnull
you could use any other value, because it has no effect.