How to Check if a Key Exists in an Associative Array in PHP?
Given an Associative array, the task is to check whether a key exists in the associative array or not. There are two methods to check if a key exists in an associative array, these are – using array_key_exists(), and isset() functions. Let’s explore each method with detailed explanations and code examples.
Table of Content
- Using array_key_exists() Function
- Using isset() Function
Approach 1: Using array_key_exists() Function
The array_key_exists() function checks if a specified key exists in an array. It returns true if the key exists and false otherwise.
<?php
$student_marks = array(
"Maths" => 95,
"Physics" => 90,
"Chemistry" => 96,
"English" => 93,
"Computer" => 98
);
// Check if the key exists in the array
if (array_key_exists('Physics', $student_marks)) {
echo "Key exists in the array";
} else {
echo "Key does not exist in the array";
}
?>
Output
Key exists in the array
Approach 2: Using isset() Function
The isset() function checks if a variable is set and is not null. When used with an array, it checks if a specified key exists in the array and is not null.
<?php
$student_marks = array(
"Maths" => 95,
"Physics" => 90,
"Chemistry" => 96,
"English" => 93,
"Computer" => 98
);
// Check if the key exists in the array
if (isset($student_marks['Physics'])) {
echo "Key exists in the array";
} else {
echo "Key does not exist in the array";
}
?>
Output
Key exists in the array
Contact Us