Skip to content
Advertisement

PHP: is there a good syntax to initialize an array element depending on whether it is undefined or not, without using if?

The double question mark syntax in PHP

JavaScript

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

JavaScript

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.

JavaScript

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:

JavaScript

Teh playground

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement