1

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.

cr001
  • 655
  • 4
  • 16
  • ```$bar1 && $a = 3;``` I think that will do it to define variable. But in your case I think it's ```$fooArr = $bar1 ? [$bar1, $bar2] : [$bar1 ]``` – Rajesh Paudel Nov 26 '21 at 11:00
  • 1
    Does this answer your question? [How to replace "if" statement with a ternary operator ( ? : )?](https://stackoverflow.com/questions/1506527/how-to-replace-if-statement-with-a-ternary-operator) – gre_gor Nov 26 '21 at 11:00
  • @gre_gor That works, but I will need to write $bar1 twice like `$bar2 ? [$bar1, $bar2] : [$bar1]`. This can becomes really long when the array consists of say 5 elements and the last element is what I want to branch on. Wondering if there is a way without the need to write down every array element twice. – cr001 Nov 26 '21 at 11:07

1 Answers1

1

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);

Teh playground

JMP
  • 4,417
  • 17
  • 30
  • 41