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.
The signature of the has
method is:
1public static function has(2 $array,3 $keys4);
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<?php2 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<?php2 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.
array_has
Helper FunctionThe array_has
function is a shortcut to calling Arr::has
. This function is declared in the global namespace.
∎
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.