Backend Development 4 min read

Understanding PHP 7.3 array_key_first(): Syntax, Usage, and Examples

PHP 7.3 introduced the array_key_first() function, which returns the first key of an array or null if empty; this article explains its syntax, demonstrates usage with examples, compares it to older approaches, and outlines scenarios such as retrieving the first key and checking for empty arrays.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP 7.3 array_key_first(): Syntax, Usage, and Examples

In PHP 7.3, the official release added a new array function— array_key_first() . This function can return the first key name of an array; if the array is empty it returns null.

Syntax

array_key_first (array $array) : mixed

Description

The array_key_first() function accepts an array argument and returns the value of its first key, or null when the array is empty.

Example 1

$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo array_key_first($arr); // outputs a

Example 2

$arr = [];
echo array_key_first($arr); // outputs null

Use Cases

1. Get the first element's key name

Previously, developers used reset() to get the first element's value and key() to obtain its key. The array_key_first() function simplifies this process.

Example:

$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo array_key_first($arr); // outputs a

2. Determine if an array is empty

Earlier, empty() or count() were used to check emptiness. Using array_key_first() provides a more straightforward way.

Example:

$arr = [];
if (array_key_first($arr) === null) {
    echo 'Array is empty';
}

Output:

Array is empty

Note that if the array contains elements with a null value, array_key_first() may behave unexpectedly.

Conclusion

The array_key_first() function, introduced in PHP 7.3, is convenient for retrieving the first key of an array and can also be used to check if an array is empty, but caution is required when the array includes null values.

PHP Practical Development Rapid Introduction

Scan the QR code to receive free learning materials

backend developmentPHParraysarray_key_firstPHP7.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

login 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.