Skip to content
Advertisement

Laravel take from collection with offset

I got this collection

$collection = collect([0, 1, 2, 3, 4, 5]);

I know I can use the method take() to bring the X first elements of the collection

$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);

$chunk->all();

// [0, 1, 2]

But I was wondering, if is there a way to add an offset to the take() method or do something that produce a result like this

$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3,2);

$chunk->all();

// [2, 3, 4]

any clue?

Advertisement

Answer

use skip method

$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->skip(2)->take(3);
$chunk->all();
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement