Laravel 5

Laravel 5 Collections: Filtering Collections Based On Value Presence With intersect

Author

John Koster

Published on April 22, 2018

The intersect removes any values that are not in the provided $items array. The intersect method returns a new instance of Collection. The intersect method preserves any keys from the original collection.

The behavior of the intersect method is similar to PHP's array_intersect function.

Signature

1public function intersect(
2 $items
3);

Example Use

The following code example highlights the usage of the intersect method:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first', 'second', 'third'
6]);
7 
8// An empty collection will be returned.
9$intersected = $collection->intersect(['fourth']);
10 
11// A collection only containing the 'third' value will
12// be returned.
13$intersected = $collection->intersect(['fourth', 'third']);

Explore The Blog