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?
CodePudding user response:
You can use the subscript operator ([]) to add elements to an array:
$body["line3"] = "test3";
CodePudding user response:
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.
