To check if an array contains a specific key in PHP, you can use the array_key_exists()
function. This function checks if a given key or index exists in an array.
Here's an example of how to use array_key_exists()
function to check if an array contains a specific key:
<?php
$array = array(
"name" => "John",
"age" => 25,
"city" => "New York"
);
if (array_key_exists("name", $array)) {
echo "The key 'name' exists!";
} else {
echo "The key 'name' does not exist!";
}
?>
In this example, the array_key_exists()
function is used to check if the key 'name' exists in the $array
. If it does, it will display "The key 'name' exists!"; otherwise, it will display "The key 'name' does not exist!".
Note that array_key_exists()
will return true
even if the value associated with the key is null
. If you want to check if the value is null
, you can use isset()
.