What is the array_key_exists method in PHP?

The array_key_exists method can be used to check if a key/index is present in an array.

Syntax

array_key_exists(string|int $key_to_check , array $array): bool

Parameters

  • key_to_check – The key will be searched in the passed array. It can be an integer or string type.

  • array – The array that is searched for key_to_check.

Return value

This method returns true if the passed key is present in the array; otherwise, false is returned.

Code

<?php
$arr = array('one' => 1, 'two' => 2, 'three' => 3);
echo "the array is \n";
print_r($arr);
echo array_key_exists('one', $arr) ? '"one" is present' : '"one" is not present';
echo "\n";
echo array_key_exists('four', $arr) ? '"four" is present' : '"four" is not present';
?>

In the code above, we create an array:

$arr = array(
  'one' => 1, 
  'two' => 2, 
  'three' => 3
);

array_key_exists('one', $arr)

We check if the key one is present in the created array by calling the array_key_exists method, with one and the created array as an argument. The key one is present in the passed array, so we will get true as a result.

array_key_exists('four', $arr)

We check if the key four is present in the array. In this case, we get false as a result because the key four is not present in the array.

Free Resources