VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-check-if-a-key-exists-in-an-associative-array-in-php/

⇱ How to Check if a Key Exists in an Associative Array in PHP? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Check if a Key Exists in an Associative Array in PHP?

Last Updated : 23 Jul, 2025

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.

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.


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.


Output
Key exists in the array

Approach 3: Using array_key_first() Function

The array_key_first() function returns the first key of the given array. We can use this function to determine if a key exists by iterating over the keys of the array.


Output
Key exists in the array

Approach 4 : Looping through Keys

To check if a key exists in an associative array in PHP, iterate through array keys using a foreach loop. Compare each key against the target key. Set a flag upon finding a match to confirm existence or absence of the key.

Example:


Output
Key 'key2' exists in the associative array.

Approach 5: Using the in_array() Function with array_keys()

The in_array() function checks if a value exists in an array. By combining it with the array_keys() function, which returns all the keys of an array, you can check if a specific key exists.

Example


Output
Key 'second' exists in the array.
Comment
Article Tags:
Article Tags: