Gilet
Gilet

Reputation: 33

How to add a new line into existing JSON

I defined a body JSON, like this:

$body = [
        "line1" => "test1",
        "line2" => "test2",
    ];

And, if a condition is true, I need to add a third line, si I'm doing this:

$body = [
        "line3" => "test3",
     ];

But what I'm doing is overwriting the $body, because when I return this, I'm getting:

{
"line3": "test3"
}

So, how can I add a third line to an existing JSON instead of overwriting it?

Upvotes: 1

Views: 128

Answers (2)

FourBars
FourBars

Reputation: 565

Well, you're generating a JSON but, before you return it like a JsonResponse, you're working with an array, so technically, your $body is an array. You can add a new line to your $body just like the same way you would add a new item to an array.

Upvotes: 2

Mureinik
Mureinik

Reputation: 311403

You can use the subscript operator ([]) to add elements to an array:

$body["line3"] = "test3";

Upvotes: 4

Related Questions