Search

Laravel 5 Collections: Filtering Collections Based on Key Presence With intersectByKeys

April 22, 2018 —John Koster

The intersectByKeys method will return a new collection containing all of the elements of the original collection that are not present in the provided array or collection.

The behavior of the intersectByKeys method is similar to PHP's array_intersect_key function.

#Signature

1public function intersectByKeys(
2 $items
3);

#Example Use

The following example demonstrates the basic usage of the intersectByKeys method:

1$contactInformation = collect([
2 'firstName' => 'John',
3 'lastName' => 'Doe',
4 'password' => 'super-secret'
5])->intersectByKeys([
6 'firstName' => '',
7 'lastName' => ''
8]);

After the above code has executed, the $contactInformation variable would reference a new collection instance with the following values:

Key Value
firstName John
lastName Doe