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

Time:08-21

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.

CodePudding user response:

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;
    }
});
  • Related