The double question mark syntax in PHP
$foo = $bar ?? null;
will return null if $bar is undefined. This syntax is extremely useful to simplify code and avoid massive if statements.
Now I have the following situation
if (!isset($bar2)) { $fooArr = [$bar1]; } else { $fooArr = [$bar1, $bar2]; }
It seems so likely that there exists a one-line simplification for the statement but I just couldn’t come up with it.
The closest I come up with is the following, but it will create an array with size 2 where the second element is null, which is not what I want.
$fooArr = [$bar1, $bar2 ?? null];
Is there a way to simplify the aforementioned nested if without using if statement?
Edit : the ? :
syntax works for the above case but I will still have to write down $bar1
twice in that situation, which is not much neater than the if statement and can grow really big when the array consists of 5 elements.
Advertisement
Answer
The array_filter()
method only returns the non-empty values from an array by default.
This code shows the various outcomes:
$bar1=1; $fooArr = [$bar1, $bar2 ?? null]; print_r($fooArr); $bar2=2; $fooArr = [$bar1, $bar2 ?? null]; print_r($fooArr); unset($bar1,$bar2); $bar1=1; $fooArr = array_filter([$bar1, $bar2 ?? null]); print_r($fooArr); $bar2=2; $fooArr = array_filter([$bar1, $bar2 ?? null]); print_r($fooArr);