0

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

1
  • 1
    What would the //ERRORs be? Commented May 21, 2021 at 9:39

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Be aware that arrow functions, i.e. the shorthand fn syntax, do not modify the variables from outer scope as stated in the PHP manual (see Example #4). It will work though if you're modifying an object since it's always passed by reference.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.