Backend Development 3 min read

Using array_key_first() in PHP 7.3: Syntax, Examples, and Use Cases

Introduced in PHP 7.3, the array_key_first() function returns the first key of an array or null for an empty array, and this article explains its syntax, demonstrates usage with code examples, and discusses practical scenarios such as retrieving the first key and checking if an array is empty.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using array_key_first() in PHP 7.3: Syntax, Examples, and Use Cases

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

Syntax

array_key_first (array $array) : mixed

Description

The function accepts an array and returns the value of its first key; if the array is empty it returns null .

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. Getting the first element's key

Before PHP 7.3 developers often used reset() together with key() to obtain the first 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. Checking if an array is empty

Instead of empty() or count() , array_key_first() can be used to test emptiness directly.

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

Result:

数组为空

Note

If the array contains an element whose value is null , using array_key_first() may lead to unexpected behavior.

Conclusion

The array_key_first() function is a convenient addition in PHP 7.3 for retrieving the first key of an array and for quickly checking whether an array is empty, but developers should be cautious when the array includes null values.

backendPHParray-functionsarray_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.