Search code examples
phplaravellaravel-collection

How can I remove filtered values from a Laravel collection within a for loop?


I would basically like to remove values from $collection to reduce the for loop duration since the filtered values are used only once.

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

foreach ($collection as $k => $v) {
    $filtered = $collection->filter(function ($value, $key) {
        return $value > 2;
    })->values(); 

    // do stuff with $filtered

    break;
}

Results that I'd like to get:

$collection = [1, 2];
$filtered = [3, 4, 5, 6, 7, 8, 9, 10];

What I'm getting currently:

$collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$filtered = [3, 4, 5, 6, 7, 8, 9, 10];

I've tried:

foreach ($collection as $k => $v) {
    $filtered = $collection->filter(function ($value, $key) use ($collection) {
        $collection->forget($key);
        return $value > 2;
    })->values(); 
}

Help would be appreciated.


Solution

  • You can try this :

    $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
     
    $filtered = $collection->filter(function ($value, $key) use ($collection) {
        if ($value > 2) {
            $collection->forget($key);
            return $value;
        }
    });