Master PHP 7.3’s array_key_first(): Retrieve the First Array Key Effortlessly

This guide explains PHP 7.3’s new array_key_first() function, showing its syntax, return behavior, practical examples for fetching the first key and checking for empty arrays, and highlights a subtle caveat when null values are present.

php Courses
php Courses
php Courses
Master PHP 7.3’s array_key_first(): Retrieve the First Array Key Effortlessly

PHP 7.3 introduced the array_key_first() function, which returns the first key of an array or null if the array is empty.

Syntax

array_key_first (array $array) : mixed

Description

The function accepts a single array argument and returns the value of its first key. If the array contains no elements, it returns null.

Example 1 – Basic Usage

$arr = ['a' => 1, 'b' => 2, 'c' => 3];

echo array_key_first($arr); // outputs a

Example 2 – Empty Array

$arr = [];

echo array_key_first($arr); // outputs null

Use Cases

1. Retrieve the first element’s key

Before PHP 7.3, developers often combined reset() to get the first value and key() to obtain its key. array_key_first() simplifies this to a single call.

$arr = ['a' => 1, 'b' => 2, 'c' => 3];

echo array_key_first($arr); // outputs a

2. Determine if an array is empty

Older code used empty() or count(). With array_key_first(), you can check for emptiness directly:

$arr = [];

if (array_key_first($arr) === null) {
    echo '数组为空';
}

Output:

数组为空

Important Note

If an array contains an element whose value is null, using array_key_first() may lead to unexpected results, so extra caution is required.

Conclusion

The array_key_first() function provides a concise way to obtain the first key of an array and to check for an empty array in PHP 7.3+, but developers should be aware of the edge case when null values are present.

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.

BackendprogrammingPHPArrayfunctionphp7.3
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

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.