PHP is assigned to an array only if it exists
2 answers
Well, you can use the ternary operator as a "shortcut":
is_null($foo) ?: $var['foo'] = $foo;
- but I would not recommend that.
This works because it $var['foo'] = $foo
is itself a valid expression - but does it "twist" the whole concept of the operator.
Edit: as others have asked and in the comments, a little more context would be helpful. If you are not asking for this out of pure curiosity, but, for example, because you need to do it for several variables, then all inserting them into an array and then using them array_filter
to "throw" the null
values โโafterwards can be more direct ...
+3
source to share