Laravel 5: Checking if an Array Contains an Element With has

April 11, 2018 —John Koster

The has helper method will return a boolean value that indicates if the given $key exists in the supplied $array, using dot notation. This method is incredibly useful when checking if an array has a specific key at an arbitrary depth.

#Signature

The signature of the has method is:

1public static function has(
2 $array,
3 $keys
4);

#Example Use

Considering the following array:

1$anArray = [
2 'nested_array_one' => [
3 'nested_array_two' => [
4 'key' => 'value'
5 ]
6 ]
7];

We can determine that the nested key actually does exist:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5$doesExist = Arr::has(
6 $anArray,
7 'nested_array_one.nested_array_two.key'
8 );

Because the nested key key does in fact exist, the value of $doesExist would be true. Inversely, we can prove that a key of does_not_exist does not, in fact, exist:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5$doesExist = Arr::has(
6 $anArray,
7 'does_not_exist'
8 );

At this point, the value of $doesExist would be false, which is accurate.

Using this method is easier to read than using PHP's isset function and checking at each level of the array whether a particular key exists.

#Global array_has Helper Function

The array_has function is a shortcut to calling Arr::has. This function is declared in the global namespace.

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.