Reputation: 13544
I have tried the following in laravel-5.4 application to use chunk
:
$out = [];
\App\User::chunk(5,function($users) use($out){
foreach($users as $user){
//$out[] = $user;
$out[] = $user->id;
}
});
dd($out);
However, the output of dd($out)
is still empty array. What's the problem here? $out
is in global scope!
Upvotes: 1
Views: 3855
Reputation: 106463
See, use
in PHP doesn't just make a variable from outer scope available within the function (similar to lexical scope in JS etc.). It copies the value of that variable (and here's more explanation, for some reason still missing in the official doc).
Take use
as a mean to pass some value inside the function without actually making it a formal parameter, a part of function's signature.
The bottom line is, you should pass the array as reference:
\App\User::chunk(5,function($users) use(&$out){
foreach($users as $user){
//$out[] = $user;
$out[] = $user->id;
}
});
Upvotes: 1
Reputation: 50531
Arrays are copy on write. You are just creating a new array in that scope when you try to write to the array you are trying to import from the parent scope.
You need to be using the reference to the array.
function ($users) use (&$out) { ... }
Upvotes: 2