Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 405
pileup Avatar asked Jun 13 '26 08:06

pileup


2 Answers

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;
}
like image 102
TomasBradleJr Avatar answered Jun 14 '26 22:06

TomasBradleJr


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;
}
like image 22
lazyme114 Avatar answered Jun 14 '26 21:06

lazyme114



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!