How to Retrieve the First Key of an Array in PHP with array_key_first()
Learn how to use PHP's array_key_first() function introduced in PHP 7.3 to obtain the first key of an array, see syntax, example code, handling empty arrays, and fallback to array_keys() for older PHP versions.
PHP is a widely used server‑side scripting language, and functions are essential. The array_key_first() function, introduced in PHP 7.3, returns the first key of an array.
Syntax: array_key_first(array $array): mixed The parameter $array is the array to operate on. The function returns the first key name, or NULL if the array is empty.
Example:
$students = array(
"Tom" => 18,
"Jerry" => 19,
"Alice" => 20
);
$first_key = array_key_first($students);
echo "The first student's name is: " . $first_key;This code defines an associative array $students where keys are names and values are ages, obtains the first key with array_key_first(), stores it in $first_key, and echoes the result, which will be “Tom”.
Note that array_key_first() is available only 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 "The first student's name is: " . $first_key;This alternative first retrieves all keys with array_keys(), then selects the first element.
Summary
The array_key_first() function, added in PHP 7.3, provides a convenient way to get an array’s first key; on older PHP versions you can use array_keys() and take the first element.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
