PHP array_key_exists() Function

PHP array_key_exists() function is used to check whether a specified key or index exists in an array.” The function returns ‘TRUE’ if the specified key is found in the array; otherwise, it returns ‘FALSE’.

Syntax

array_key_exists(key, $array)

Parameters

  1. key(required): It is the value of the key to be checked.
  2. array(required): It is an input array in which the key will be checked.

Return value

The function returns a boolean value, i.e., TRUE or FALSE, depending on whether the key is present in the array.

Visual RepresentationVisual Representation of PHP array_key_exists() Function

Example 1: How to Use PHP array_key_exists()

<?php

 $arr = array("eleven" => 11, "dustin" => 21, "will" => 30, "nancy" => 40);

 if (array_key_exists("dustin", $arr))
 {
   echo "Key exists!";
 }
 else
 {
   echo "Key does not exist!";
 }

Output

Key exists!

In this example,key_exists() checks whether “dustin” exists in an array $arr. Since “dustin” is indeed a key in the array, it returns Key exists!

Example 2: Checking the indexed array keysVisual Representation of Checking the indexed array keys

<?php

 $arr = array("eleven", "dustin", "will", "nancy");

 if (array_key_exists(3, $arr))
 {
   echo "Key exists!";
 }
 else
 {
   echo "Key does not exist!";
 }

Output

Key exists!

Example 3: Passing an empty array

Passing an empty array to the array_key_exists() function won’t return anything because no key exists.

<?php

 $arr = array();

 if (array_key_exists(0, $arr))
 {
   echo "Key exists!";
 }
 else
 {
   echo "Key does not exist!";
 }

Output

Key does not exist!

Example 4: Compare Performance array_key_exists with isset()

To take the performance advantage of isset() while correctly detecting the NULL element.

Benchmark (100000 runs):
array_key_exists(): 205 ms
is_set(): 35ms
isset() || array_key_exists(): 48ms

The above note on this page states that the isset() is significantly faster than array_key_exists(). It may be true except for one small hitch.

<?php

$eddie = array();
$eddie['broke'] = NULL;

var_dump(isset($eddie['broke']));
var_dump(array_key_exists('broke', $eddie));

Output

bool(false) 
bool(true)

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.