Using PHP’s array_key_first() Function to Retrieve the First Key of an Array
This article explains the PHP 7.3+ array_key_first() function, shows its syntax and a practical example for obtaining the first key of an associative array, and provides a fallback method using array_keys() for older PHP versions.
PHP is a widely used server‑side scripting language and functions are essential to its programming; the array_key_first() function, introduced in PHP 7.3, returns the first key of an array.
The function’s syntax is:
array_key_first(array $array): mixedIn the example, an associative array $students is defined with names as keys and ages as values. The call $first_key = array_key_first($students); stores the first key ("Tom") in $first_key , which is then echoed to produce the output "第一个学生的姓名是:Tom".
If the PHP version is lower than 7.3, array_key_first() is unavailable; the same result can be achieved by retrieving all keys with array_keys($students) and selecting the first element, as shown in the alternative code snippet.
Both approaches allow developers to flexibly obtain the first key of an array, facilitating further array manipulation.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.