0

I have a json array: $json = [];

Then in a loop I add data to it, and these fields have nested structure:

$json[] = [
   "key1" => "value1",
   "key2" => array(
       "key3" => "value3",
       "key4" => "value4",                   
       "foo" => $bar 
    )
];

How can I add the key foo only if $bar is set, otherwise not add it at all?

The following doesn't work:

$json[] = [
   "key1" => "value1",
   "key2" => array(
       "key3" => "value3",
       "key4" => "value4",                   
       "foo" => $bar ?? null 
    )
];

$bar is also an array if that matters

11

1 Answer 1

1

Here's an example code for conditionally adding $bar to json['key2']['foo']:

// some loop
while (true) {
    $bar = []; // set bar to array or null

    $key2 = [
        "key3" => "value3",
        "key4" => "value4"
    ];

    if (isset($bar)) { // or empty($bar)
        $key2['foo'] = $bar;
    }

    $json[] = [
        "key1" => "value1",
        "key2" => $key2
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.