LAST UPDATED: AUGUST 4, 2021
How to check if a key exists in an array in PHP?
Answer: Using array_key_exists()
function
We can check if a key exists in an array using the PHP built-in function named array_key_exists()
function.
This function checks whether a specified key exists within the array or not. It returns TRUE if it exists within the array. Otherwise, it returns FALSE.
The key can be any value possible for an array index.
Example: Using array_key_exists()
function
In the given example, we have check whether the specified key Jack exists within the array $empID or not using the array_key_exists()
function.
<!DOCTYPE html>
<html>
<head>
<title>Check if a key exists in an array</title>
</head>
<body>
<?php
$empID = array("Jack" => 110, "Henry" => 111, "Miley" => 112, "Cairo" => 113);
if(array_key_exists("Jack", $empID)){
echo "Key exists";
}else {
echo "Key doesn't exists";
}
?>
</body>
</html>
Key exists
Using isset()
function
We can also check if a key exists within the given array using PHP built-in isset()
function. This function checks whether a variable is set or not, which means the variable should be declared, and the value of the variable should not be null.
The isset()
function does not return true if the value of the specified key is null. This function returns true if the key is present within the array and the value of the key is not null.
Example: Using isset()
function
In the given example, we have checked whether the Key Jack exists within the array $empID or not using the isset()
function.
<!DOCTYPE html>
<html>
<head>
<title>Check if a key exists in an array</title>
</head>
<body>
<?php
$empID = array("Jack" => 110, "Henry" => 111, "Miley" => 112, "Cairo" => 113);
if(isset($empID["Jack"])){
echo "Key exists";
}else {
echo "Key doesn't exists";
}
?>
</body>
</html>
Key exists
Conclusion
In this lesson, we have learned how to check if a key exists within the array or not. PHP offers several built-in functions to check whether the key exists within the array or not. First, we have used the array_key_exists()
function to check whether the specified key exists within the array or not. After that, we have used the isset()
function to check for the same. The isset()
function does not return true if the value of the specified key is null while the array_key_exists()
function returns true.