I am currently using this code to assign a variable into the array only if it does not carry a null reference. Is their any shortcut/alternative method?
if (!is_null($foo)) {
$var['foo'] = $foo;
}
if (!is_null($bar)) {
$var['bar'] = $bar;
}
I am currently using this code to assign a variable into the array only if it does not carry a null reference. Is their any shortcut/alternative method?
if (!is_null($foo)) {
$var['foo'] = $foo;
}
if (!is_null($bar)) {
$var['bar'] = $bar;
}
Well you could use the ternary operator as a “shortcut”:
is_null($foo) ?: $var['foo'] = $foo;
– but I would not really recommend this.
It works because $var['foo'] = $foo in itself is a valid expression – but is it kinda “perverting” the whole concept of the operator a bit.
Edit: As other have asked in comments as well, a little more context would be helpful. If you are not asking this out of pure curiosity, but for example because you have to do this for multiple variables – then putting them all into the array in any case, and then using array_filter to “throw away” the null values afterwards might be more straight forward …