Search

Laravel Array Helper Function: Checking If a Key Exists in an Array or Collection

November 20, 2016 —John Koster

exists($array, $key)

The exists helper method is similar to PHP's array_key_exists function in that in can be used to check if the given $key or index exists with the provided $array. The exists method defines two parameters, and both are required.

Any value that returns true from the Arr::accessible helper method can be used as a value for $array.

The following examples demonstrate the usage of the exists method. The results of the method call will appear above the call as a comment.

1<?php
2 
3use Illuminate\Support\Arr;
4 
5// Create some test data to work with.
6$array = [
7 'first_name' => 'Jane',
8 'last_name' => 'Doe'
9];
10 
11$collection = collect($array);
12$model = factory('App\User')->make();
13 
14// true
15Arr::exists($array, 'first_name');
16Arr::exists($array, 'last_name');
17 
18// false
19Arr::exists($array, 'middle_name');
20 
21// true
22Arr::exists($collection, 'first_name');
23Arr::exists($collection, 'last_name');
24 
25// false
26Arr::exists($collection, 'middle_name');
27 
28// true
29Arr::exists($model, 'name');
30Arr::exists($model, 'email');
31Arr::exists($model, 'remember_token');
32 
33// false
34Arr::exists($model, 'first_name');

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.