2

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

2 Answers 2

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

3

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;
}

1 Comment

In an isset && !empty construct, the isset is always redundant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.