PHP array_key_exists Function | Check If Key Exists in Array

PHP array_key_exists is an inbuilt Function in PHP. It checks if a given key or index exists in an array or not. In this article, we will discuss the PHP array_key_exists Function. Also, we will discuss a few examples demonstrating it. We will also discuss the difference between PHP isset and array_key_exists Function.


boolean array_key_exists($index, $array)


The PHP array_key_exists Function expects two mandatory parameters. The description of the parameters is as follows:

  • $index: The first parameter is a mandatory string index which you need to check in the array.
  • $array: The second parameter is a mandatory array in which you need to check for the key.

The array_key_exists works only on single dimensional arrays. It does not search for keys in multi-dimensional arrays.

Return Value

The Function returns a boolean value. It returns true if the key exists in the array. Otherwise, it returns false.

PHP array_key_exists Function Diagram
PHP arary_key_exists Function Diagram


Let’s go through some Examples.

Example 1: Basic Array Search

For instance, consider the following example.


	$testArray = array('a' => 'apple', 'b' => 'banana', 'c' => 'cat', 'd' => array('e' => 'elephant'));
	var_dump(array_key_exists('b', $testArray));
	/* true */ //The key b exists in the array and is set

	var_dump(array_key_exists('z', $testArray));
	/* true */ //The key z does not exist in the array

	var_dump(array_key_exists('e', $testArray));
	/* true */ //The key exists but in the nested array


In the above example, you can observe the following things:

  • The key ‘a’ exists in the array. Hence, PHP array_exists Function returns true.
  • The key ‘z’ does not exist in the array. Therefore, the function returns false.
  • The key ‘e’ exists but in the nested array. The function again returns false as it does not check for multi-dimensional arrays.

Example 2: Difference Between isset and array_key_exists

The PHP isset Function does not return true if the value of the corresponding key is null. However, the array_key_exists Function returns true even if the value of the key is null. This can be observed in the following example:


	$testArray = array('a' => 'apple', 'b' => null);

	/* false */ //The value of b is null and isset returns false

	var_dump(array_key_exists('b', $testArray));
	/* true */ //The value of b is null but array_key_exists returns true as the key exists

Essentially, the array_key_exists function checks if the key exists or not. However, it returns true even if the value of the key is null.


We discussed the PHP array_key_exists Function in this article. You can learn more about it on its Official PHP Documentation. Also, you can learn about more Array Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *