Mastering PHP’s array_key_exists: Check If a Key Exists in an Array
This guide explains how the PHP function array_key_exists works, details its parameters and return values, and provides two clear code examples showing how to verify the presence of keys in both arrays and objects.
The PHP function array_key_exists() returns TRUE when a specified key or index is present in an array (or object) and FALSE otherwise. The key can be any value that is valid as an array index.
Function Signature
bool array_key_exists(mixed $key, array $search)Parameters
$key : The key to check for.
$search : The array (or object) in which to look for the key.
Return Value
Returns TRUE on success (key exists) and FALSE on failure.
Example 1 – Basic Array Check
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>This script creates an associative array and uses array_key_exists() to test whether the key 'first' is present, printing a message when it is.
Example 2 – Comparing with isset()
<?php
$search_array = array('first' => null, 'second' => 4);
// array_key_exists returns true because the key exists even though its value is null
var_dump(array_key_exists('first', $search_array)); // bool(true)
// isset returns false because the value is null
var_dump(isset($search_array['first'])); // bool(false)
?>This example demonstrates that array_key_exists() checks for the existence of the key regardless of its value, whereas isset() returns false for keys with null values.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
