Backend Development 3 min read

Using PHP’s array_key_first() Function to Retrieve the First Array Key

Introduced in PHP 7.3, the array_key_first() function returns the first key of an array, with examples showing its usage, handling of empty arrays, and an alternative approach using array_keys() for older PHP versions.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP’s array_key_first() Function to Retrieve the First Array Key

PHP is a widely used server‑side scripting language, and functions are essential; the array_key_first() function was introduced in PHP 7.3 to retrieve the first key of an array.

The syntax is:

array_key_first(array $array): mixed

The function accepts an array as its argument and returns the first key, or NULL if the array is empty.

Example usage:

$students = array("Tom" => 18, "Jerry" => 19, "Alice" => 20); $first_key = array_key_first($students); echo "第一个学生的姓名是:" . $first_key;

In this example, the array $students maps student names to ages; array_key_first() returns the first key ("Tom") which is stored in $first_key and printed.

Note that array_key_first() is only available in PHP 7.3 and later. For earlier versions you can achieve the same result with array_keys() :

$students = array("Tom" => 18, "Jerry" => 19, "Alice" => 20); $keys = array_keys($students); $first_key = $keys[0]; echo "第一个学生的姓名是:" . $first_key;

This alternative first obtains all keys with array_keys() , selects the first element, and outputs it.

In summary, array_key_first() provides a convenient way to get the first key of an array in PHP 7.3+, while array_keys() can be used as a fallback for older versions.

Backend DevelopmentPHParray-functionsarray_key_firstPHP 7.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.