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:
<code>array_key_first(array $array): mixed</code>The parameter
$arrayis the array to operate on. The function returns the first key name, or
NULLif 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
$studentswhere 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.
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.