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

Time:08-29

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

CodePudding user response:

Why not check before setting, like

if $foo is array

if(isset($foo) && !empty($foo)) {
    $array['foo'] = $foo;
}

if $foo is string

if(isset($foo) && $foo != "") {
    $array['foo'] = $foo;
}

CodePudding user response:

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;
}
  •  Tags:  
  • php
  • Related