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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Mastering PHP’s array_key_exists: Check If a Key Exists in an Array

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendarray_key_existskey existence
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.