phplaravelcollectionseacharray-push

Laravel : array_push not working in collection->each() iterator


I have grouped collection and I iterate it using each() function.Inside the each function I want to add element to some array.But it is not working.Any idea?

$dataSet1 = [];

$appointments = [
         ['department' => 'finance', 'product' => 'Chair'],
         ['department' => 'marketing', 'product' => 'Bookcase'],
         ['department' => 'finance', 'product' => 'Desk'],
]; 
$groupData = collect($appointments)->groupBy('department');

$groupData->each(function ($item, $key) {
   Log::info($key); //Show correct output in log
   array_push($dataSet1, $key); //ERROR
   array_push($dataSet1, 'A');//ERROR
});

Laravel version : 8.35.1


Solution

  • You need to pass the array to the function with use:

    $groupData->each(function ($item, $key) use (&$dataSet1) {
       Log::info($key); //Show correct output in log
       array_push($dataSet1, $key); //ERROR
       array_push($dataSet1, 'A');//ERROR
    });
    

    Pass-by-reference (&) is needed as long as $dataSet1 is not an object instance.