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);<br/>$first_key = array_key_first($students);<br/>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);<br/>$keys = array_keys($students);<br/>$first_key = $keys[0];<br/>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.

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.

Backend Developmentarray 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

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.