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

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

Laravel 5

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

public function contains(
    $key,
    $operator = null,
    $value = null
);

Example Use

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

use Illuminate\Support\Collection;

// Create a new collection instance.
$collection = new Collection([
    'bear',
    'whale',
    'chicken',
    'tardigrade'
]);

// true
$collection->contains('bear');

// true
$collection->contains('tardigrade');

// false
$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:

use Illuminate\Support\Collection;

// Create a new collection instance.
$collection = new Collection([
    ['big'     => 'bear'],
    ['bigger'  => 'whale'],
    ['small'   => 'chicken'],
    ['smaller' => 'tardigrade']
]);

// true
$collection->contains('big', 'bear');

// true
$collection->contains('smaller', 'tardigrade');

// false
$collection->contains('smaller', 'paramecium');

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

use Illuminate\Support\Collection;

class User
{

    /**
     * A hypothetical user's first name.
     * 
     * @var string
     */
    public $firstName = '';

    /**
     * A hypothetical user's favorite number.
     * 
     * @var integer
     */
    public $favoriteNumber = 0;

    public function __construct($firstName, $favoriteNumber)
    {
        $this->firstName      = $firstName;
        $this->favoriteNumber = $favoriteNumber;
    }

}

// Create a new collection instance.
$collection = new Collection([
    new User('Jane', 7),
    new User('Sarah', 9),
    new User('Ben', 2)
]);

// true
$collection->contains('firstName', 'Jane');

// false
$collection->contains('firstName', 'Josh');

// false
$collection->contains('lastName', 'Jane');

// true
$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:

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

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:

// true
$collection->contains(function($value, $key) {
    return (
               $value->favoriteNumber >= 7 &&
               $value->favoriteNumber <= 9
           );
});

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:

use Illuminate\Support\Collection;

$collection = new Collection([
    'first', 'second', 'third'
]);

// true
$collection->contains('third');

// true
$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:

// true
$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:

class User
{

    /**
     * A hypothetical user's first name.
     *
     * @var string
     */
    public $firstName = '';

    public function __construct($firstName)
    {
        $this->firstName = $firstName;
    }

    /**
     * Indicates whether or not the user is an admin.
     *
     * @return bool
     */
    public function isAdmin()
    {
        return true;
    }

}

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):

$users = collect([
    'Alice', 'Bob', 'Charlie'
])->transform(function ($name) {
   return new User($name);
});

$containsAdmins = $users->contains->isAdmin();

Start the Discussion

Leave a comment

Subscribe to our newsletter