The php array_key_exists() function checks an array to see if a given key exists in that array.

$array = array("black" => "bear", "grey" => "elephant", "yellow" => "lion");


// Output: 

When working with arrays in php, it can be valuable to be able to easily gather information of the properties of an array.

One such situation is if you want to know if a key exists in an array.

In php, we can use the array_key_exists() function to check an array for the existence of a specific key.

array_key_exists() takes two parameters. The first parameter is the value of the key you want to check, and the second parameter is the array to check.

If the key exists, array_key_exists() will return TRUE. If it doesn’t exist, array_key_exists() returns FALSE.

Below are some examples of how to use the php array_key_eixsts() function to find out if a key exists in an given array.

$array1 = array("black" => "bear", "grey" => "elephant", "yellow" => "lion");
$array2 = array(100,101,102);


// Output: 

Checking if a Key Exists in an Array with php isset() Function

You can also check if a key exists in an array with the php isset() function.

The isset() function in php takes one or more variables and checks to see if the variable is declared and is different than null.

isset() returns TRUE if the variable exists and FALSE if the variable hasn’t been declared or is null.

We can use isset() to check if a key in an array exists as shown in the following php code.

$array = array("black" => "bear", "grey" => "elephant", "yellow" => "lion");


// Output: 

Categorized in:


Last Update: February 26, 2024