By John Koster
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
.
#Signature
The signature of the exists
method is:
1public static function exists(
2 $array,
3 $key
4);
#Example Use
The following examples demonstrate the usage of the exists
method. The results of the method call will appear above the call as a comment.
1use Illuminate\Support\Arr;
2
3// Create some test data to work with.
4$array = [
5 'first_name' => 'Jane',
6 'last_name' => 'Doe'
7];
8
9$collection = collect($array);
10$model = factory('App\User')->make();
11
12// true
13Arr::exists($array, 'first_name');
14Arr::exists($array, 'last_name');
15
16// false
17Arr::exists($array, 'middle_name');
18
19// true
20Arr::exists($collection, 'first_name');
21Arr::exists($collection, 'last_name');
22
23// false
24Arr::exists($collection, 'middle_name');
25
26// true
27Arr::exists($model, 'name');
28Arr::exists($model, 'email');
29Arr::exists($model, 'remember_token');
30
31// false
32Arr::exists($model, 'first_name');
∎