Skip to content
Advertisement

Add key-value pair to array only if variable is set

I am adding key-value pairs to my array like so:

JavaScript

And I want to add another key foo, only if the variable $bar is set:

JavaScript

How to add the "foo" => $foo pair only if $foo is set?

What I do right now is to add empty ("") value to the key "foo" if $bar is not set, but I want to not add it at all

Advertisement

Answer

Every time I need to fill array based on some condition, I do something like this:

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