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:

$array[] =
    [
        "key1" => "value1",
        "key2" => "value2",
        // ...
    ]

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

$array[] =
    [
        "key1" => "value1",
        "key2" => "value2",
        "foo"  => $bar
        // ...
    ]

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:

$array = [];
$array['key1'] = 'value1';
$array['key2'] = 'value2';
    
if (isset($bar)) {
    $array['foo'] = $bar;
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement