PHP 8.3.4 Released!

array_key_first

(PHP 7 >= 7.3.0, PHP 8)

array_key_firstGets the first key of an array

Description

array_key_first(array $array): int|string|null

Get the first key of the given array without affecting the internal array pointer.

Parameters

array

An array.

Return Values

Returns the first key of array if the array is not empty; null otherwise.

Examples

Example #1 Basic array_key_first() Usage

<?php
$array
= ['a' => 1, 'b' => 2, 'c' => 3];

$firstKey = array_key_first($array);

var_dump($firstKey);
?>

The above example will output:

string(1) "a"

Notes

Tip

There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys(), but that may be rather inefficient. It is also possible to use reset() and key(), but that may change the internal array pointer. An efficient solution, which does not change the internal array pointer, written as polyfill:

<?php
if (!function_exists('array_key_first')) {
function
array_key_first(array $arr) {
foreach(
$arr as $key => $unused) {
return
$key;
}
return
NULL;
}
}
?>

See Also

  • array_key_last() - Gets the last key of an array
  • reset() - Set the internal pointer of an array to its first element
add a note

User Contributed Notes 2 notes

up
0
MaxiCom dot Developpement at gmail dot com
3 months ago
A polyfill serves the purpose of retroactively incorporating new features from PHP releases into older PHP versions, ensuring API compatibility.

In PHP 7.3.0, the array_key_first() function was introduced, demonstrated in the following example:

<?php

$array
= [
'first_key' => 'first_value',
'second_key' => 'second_value',
];

var_dump(array_key_first($array));

?>

The provided polyfill in this documentation allows the convenient use of array_key_first() with API compatibility in PHP versions preceding PHP 7.3.0, where the function was not implemented:

<?php

if (!function_exists('array_key_first')) {
function
array_key_first(array $arr) {
foreach (
$arr as $key => $unused) {
return
$key;
}
return
null;
}
}

$array = [
'first_key' => 'first_value',
'second_key' => 'second_value',
];

var_dump(array_key_first($array));

?>
up
-20
Anonymous
7 months ago
The best way to polyfill array_key_first is:

$first_key = array_keys($array)[0] ?? NULL;
To Top