Skip to content
Advertisement

laravel – Can I add new items to an array that already has some existing items?

var_export($response) is an array like below:

array (
   0 =>
    array (
    'courseId' => 14,
    'tutorName' => 'admin',
    ),
   1 =>
    array (
    'courseId' => 15,
    'tutorName' => 'merl',
    ),
 )

The below code gives a result like this: "data": 3. I wanted add a new item called points with the $response array, into all elements. But here, it overwrites the existing array. How can I achieve this?

$dat=array_push($response,array('points'=>"3"));
return response()->json(['data' => $dat], 200);

Expected output:

[
    {
        "courseId": 14,
        "tutorName": "admin",
        "points": 3
    },
    {
        "courseId": 15,
        "tutorName": "merl",
        "points": 3
    }
]

Advertisement

Answer

As mentioned, array_push() returns the new number of elements in the array. That’s why you get 3.

You can add your value in all elements of the current response, like this:

foreach ($response as $key => $value) {
    $response[$key]['points'] = 3;
}

Then, just return the response :

return response()->json($response, 200);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement