Laravel 5 Collections: Determining If a Collection Contains an Element With contains

April 22, 2018 —John Koster

The contains method is used to determine if a given $key exists within the collection. Additionally, an optional $value can be specified that will be used to check if a given key/value pair exists within the collection. The contains method is incredibly versatile, and each use case will be highlighted below.

#Signature

1public function contains(
2 $key,
3 $operator = null,
4 $value = null
5);

#Example Use

The following demonstrates the contains method in its most basic usage:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'bear',
6 'whale',
7 'chicken',
8 'tardigrade'
9]);
10 
11// true
12$collection->contains('bear');
13 
14// true
15$collection->contains('tardigrade');
16 
17// false
18$collection->contains('dog');

The following demonstrates using the contains method to check if a given key/value pair exists in a collection that contains arrays as items:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 ['big' => 'bear'],
6 ['bigger' => 'whale'],
7 ['small' => 'chicken'],
8 ['smaller' => 'tardigrade']
9]);
10 
11// true
12$collection->contains('big', 'bear');
13 
14// true
15$collection->contains('smaller', 'tardigrade');
16 
17// false
18$collection->contains('smaller', 'paramecium');

The following example shows how the contains method can be used on collections of objects, using a hypothetical User class:

1use Illuminate\Support\Collection;
2 
3class User
4{
5 
6 /**
7 * A hypothetical user's first name.
8 *
9 * @var string
10 */
11 public $firstName = '';
12 
13 /**
14 * A hypothetical user's favorite number.
15 *
16 * @var integer
17 */
18 public $favoriteNumber = 0;
19 
20 public function __construct($firstName, $favoriteNumber)
21 {
22 $this->firstName = $firstName;
23 $this->favoriteNumber = $favoriteNumber;
24 }
25 
26}
27 
28// Create a new collection instance.
29$collection = new Collection([
30 new User('Jane', 7),
31 new User('Sarah', 9),
32 new User('Ben', 2)
33]);
34 
35// true
36$collection->contains('firstName', 'Jane');
37 
38// false
39$collection->contains('firstName', 'Josh');
40 
41// false
42$collection->contains('lastName', 'Jane');
43 
44// true
45$collection->contains('favoriteNumber', 2);

A function can also be supplied as the only argument to the contains method. The following example demonstrates how to determine if there are any user's that have favorite numbers greater than 7:

1// true
2$collection->contains(function($value, $key) {
3 return $value->favoriteNumber > 7;
4});

It should be noted that in the above example that the $value will be an instance of the User class. Additionally, truth tests can be as complex as required. The following will determine if there are any favorite numbers between 7 and 9, including 7 and 9:

1// true
2$collection->contains(function($value, $key) {
3 return (
4 $value->favoriteNumber >= 7 &&
5 $value->favoriteNumber <= 9
6 );
7});

#Considerations of the contains Method

The contains method defines two parameters: $key and $value. The $value parameter has a default value of null, however, the two method calls are not the same:

1use Illuminate\Support\Collection;
2 
3$collection = new Collection([
4 'first', 'second', 'third'
5]);
6 
7// true
8$collection->contains('third');
9 
10// true
11$collection->contains('third', null);

Even though the two examples return true, the second example is functionally not correct. When explicitly passing null as the second argument, the contains method will always return true:

1// true
2$collection->contains('fourth', null);

The above example returns true even though fourth is not in the collection.

#Using contains With Higher Order Messages

The contains method can also be used with higher order messaging, which allows us to invoke collection methods and access properties on objects using PHP's property accessors syntax. In the following example, we will modify the User class we created earlier in this section:

app/User.php:

1class User
2{
3 
4 /**
5 * A hypothetical user's first name.
6 *
7 * @var string
8 */
9 public $firstName = '';
10 
11 public function __construct($firstName)
12 {
13 $this->firstName = $firstName;
14 }
15 
16 /**
17 * Indicates whether or not the user is an admin.
18 *
19 * @return bool
20 */
21 public function isAdmin()
22 {
23 return true;
24 }
25 
26}

With the modified User class in place, we can now use higher order messages to determine if the collection contains administrators (in our example, this will always return true since the isAdmin method always returns true):

1$users = collect([
2 'Alice', 'Bob', 'Charlie'
3])->transform(function ($name) {
4 return new User($name);
5});
6 
7$containsAdmins = $users->contains->isAdmin();

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.