diff --git a/src/Collection.php b/src/Collection.php index 5434f83bc..76e35b139 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -134,6 +134,21 @@ public function map(callable $callback): self return new self($items); } + /** + * Run callback on each item of the collection an remove it if it does not return true + * + * @param callable $callback + * @return Collection + */ + public function filter(callable $callback): self + { + $items = array_filter($this->items, function ($item) use ($callback) { + return $callback($item); + }); + + return new self($items); + } + public function pushEach(array $data, ?callable $callback = null): CollectionInterface { if (! is_iterable($data)) { diff --git a/tests/CollectionTest.php b/tests/CollectionTest.php index 9703486ef..67488a62e 100644 --- a/tests/CollectionTest.php +++ b/tests/CollectionTest.php @@ -45,6 +45,16 @@ public function testCount() $this->assertEquals(3, count($collection)); } + public function testFilter() + { + $collection = new Collection(['foo', 'bar', 'baz']); + $this->assertEquals(3, $collection->count()); + $collection = $collection->filter(function ($text) { + return substr($text, 0, 1) == 'b'; + }); + $this->assertEquals(2, $collection->count()); + } + public function testFirstLast() { $collection = new Collection(['foo', 'bar', 'baz']);