Published in Laravel

Laravel Collection Public API: intersect

By John Koster

intersect($items)

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 following code example highlights the usage of the intersect method:

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