Backend Development 3 min read

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中文网 Courses
php中文网 Courses
php中文网 Courses
How to Retrieve the First Key of an Array in PHP with array_key_first()

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:

<code>array_key_first(array $array): mixed</code>

The parameter

$array

is the array to operate on. The function returns the first key name, or

NULL

if the array is empty.

Example:

<code>$students = array(
    "Tom"   => 18,
    "Jerry" => 19,
    "Alice" => 20
);
$first_key = array_key_first($students);
echo "The first student's name is: " . $first_key;
</code>

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()

:

<code>$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;
</code>

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.

backendPHPFunctionsarray_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.