In this tutorial, you shall learn about PHP array_key_exists() function which can check if a specific key is present in the array, with syntax and examples.

PHP arraykeyexists Function

The PHP array_key_exists() function checks if a specific key exists in the array. The function returns TRUE if the key is present, else it returns FALSE.

array_key_exists() function works for both indexed arrays and associative arrays. For indexed arrays, index is the key.

Syntax of arraykeyexists

The syntax of array_key_exists() function is

array_key_exists( key, array)

where

Parameter Description
key [mandatory] The key which we have to search in an array.
array [mandatory] The array in which we have to search the key.

Function Return Value

array_key_exists() returns boolean value TRUE if the key exists and FALSE if the key does not exist.

Examples

1 Check if the array contains the key m

In this example, we will take an associative array with key-value pairs, and check if specific key "m" is present in the array.

PHP Program

<?php
$array1 = array("a"=>"apple", "b"=>"banana", "m"=>"mango", "o"=>"orange");
$key = "m";
if (array_key_exists($key, $array1)) {
    echo "Key exists in the array!";
} else {
    echo "Key does not exist in the array!";
}
?>

Output

array_key_exists() returns TRUE for the given array and specified key. So, if block is executed.

2 arraykeyexists for Indexed Array

In this example, we will check if a specific index (key) is present in the array.

PHP Program

<?php
$array1 = array("apple", "banana", "mango", "orange");
$key = "2";
if (array_key_exists($key, $array1)) {
    echo "Key exists in the array!";
} else {
    echo "Key does not exist in the array!";
}
?>

Output

The array is also printed to the console to understand the index of items in the array.

Conclusion

In this PHP Tutorial, we learned how to , using PHP Array array_key_exists() function.