PHP Function Reference

PHP array_key_exists() Function



The PHP array_key_exists() function checks if the given key or index exists in the array. It returns true if the specified key is set in the array. key can be any value possible for an array index.

Syntax

array_key_exists(key, array)

Parameters

key Required. Specify key to check.
array Required. Specify an array with keys to check.

Return Value

Returns true on success or false on failure.

Note: array_key_exists() searches for the keys in the first dimension only. Nested keys in multi-dimensional arrays will not be found.

Exceptions

NA.

Example:

The example below shows the usage of array_key_exists() function.

<?php
$Arr = array("Red" => 1, 
             "Green" => 2, 
             "Blue" => 3);

//checking 'White' key in the array
if(array_key_exists("White", $Arr)) {
  echo "Array contains 'White' key.\n";
} else {
  echo "Array does not contain 'White' key.\n";  
}

//checking 'Green' key in the array
if(array_key_exists("Green", $Arr)) {
  echo "Array contains 'Green' key.\n";
} else {
  echo "Array does not contain 'Green' key.\n";  
}
?>

The output of the above code will be:

Array does not contain 'White' key.
Array contains 'Green' key.

Example:

Consider one more example where the array_key_exists() function is used with an index array.

<?php
$Arr = array(10, 20, 30, 40);

//checking if index=2 is set or not
if(array_key_exists(2, $Arr)) {
  echo "index=2 is set.\n";
} else {
  echo "index=2 is not set.\n";  
}

//checking if index=5 is set or not
if(array_key_exists(5, $Arr)) {
  echo "index=5 is set.\n";
} else {
  echo "index=5 is not set.\n";  
}
?>

The output of the above code will be:

index=2 is set.
index=5 is not set.

❮ PHP Array Reference