Check if an Array contains a key in PHP

This tutorial will discuss about unique ways to check if an array contains a key in php.

Table Of Contents

Method 1: Using array_key_exists() function

The array_key_exists() function in PHP, accepts a key and an array as arguments, and returns true, if the given key exists in the array. Otherwise it returns false.

So, we can use this array_key_exists() function to check if an array contains a key or not.

Let’s see the complete example,

<?php
$arr = array('Name' => 'Ritika', 'City' => 'Delhi');
$key = 'Name';

# Check if key "Name" exists in the array
if (array_key_exists($key, $arr)) {
    echo "Yes, Key exists in the array";
} else {
    echo "No, Key does not exists in the array";
}
?>

Output

Yes, Key exists in the array

Method 2: Using isset() function

The isset() function in PHP, accepts a variable as an argument, and returns true if the given variable is declared and has value different than null. So, to check if a key exists in array, we can select the entry in the array with that key i.e. $arr[$key] and pass it to isset() function. If it returns true, then it means that the given key exists in the array.

Let’s see the complete example,

<?php
$arr = array('Name' => 'Ritika', 'City' => 'Delhi');
$key = 'Name';

# Check if key "Name" exists in the array
if (isset($arr[$key])) {
    echo "Yes, Key exists in the array";
} else {
    echo "No, Key does not exists in the array";
}
?>

Output

Yes, Key exists in the array

Summary

We learned about two different ways to check if an array contains a key or not in PHP. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top