Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ajvanho's avatar
Level 14

Array from chunk

I have problem to make array with chunk... ‘’’’ DB::table('users')->chunk(100, function($users) {

$data = [];

foreach ($users as $user)
{
    $data[] = $user->name++
}

dd($data); // array of only 100 pairs?!?

}); ‘’’

0 likes
5 replies
jlrdw's avatar
$data = [];

DB::table('users')->chunk(100, function ($users) {
   foreach ($users as $user) {
        $data[] = $user->name;
    }


    return false;
});

dd($data);

Try with $data = []; there first and if it doesn't work try with $data = []; above the foreach.

1 like
lukasyelle's avatar

Try with this:

$data = [];

DB::table('users')->chunk(100, function ($users) use ($data) {
   foreach ($users as $user) {
        $data[] = $user->name;
    }


    return false;
});

dd($data);

The closure defined in the chunk method will not share the global variable scope, so you have to "use" it.

1 like
MichalOravec's avatar
Level 75

This will work

$data = [];

DB::table('users')->chunk(100, function ($users) use (&$data) {    
    foreach ($users as $user) {
        $data[] = $user->name;
    }
});

dd($data);

There is reference &

But basically

$data = DB::table('users')->pluck('name');
2 likes

Please or to participate in this conversation.