6

Check if an Array contains a key in PHP

 1 year ago
source link: https://thispointer.com/check-if-an-array-contains-a-key-in-php/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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,

Advertisements

<?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";
?>
<?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
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";
?>
<?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
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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK