
Resetting the array keys after filtering a collection
28 May 2022 #pattern #development #laravel #php
I'm a big fan of using collections in Laravel.
When you filter a collection in Laravel, you might have noticed that it keeps the original array indexes.
Imagine you have the following collection:
$collection = collect([ 1 => ['fruit' => 'Pear', 'price' => 100], 2 => ['fruit' => 'Apple', 'price' => 300], 3 => ['fruit' => 'Banana', 'price' => 200], 4 => ['fruit' => 'Mango', 'price' => 500]]);
When you filter the collection to retrieve all elements with a price higher than 200, you get:
$filtered = $collection->filter(fn ($item) => $item['price'] > 200)->all();
[ 2 => [ "fruit" => "Apple", "price" => 300, ], 4 => [ "fruit" => "Mango", "price" => 500, ],]
PS: I'm using the all
method to get the result as a plain array.
Notice that the indexes are preserved. Sometimes, this can be annoying. There is however an easy fix by using the values
method on the collection after the filtering.
$collection->filter(fn ($item) => $item['price'] > 200)->values()->all();
[ [ "fruit" => "Apple", "price" => 300, ], [ "fruit" => "Mango", "price" => 500, ],]