(PHP 7 >= 7.3.0, PHP 8)
array_key_first — Recupera la primera clave de un array
Recupera la primera clave del array array dado sin
afectar el puntero interno del array.
arrayUn array.
Devuelve la primera clave de array si el array no está
vacío; null en caso contrario.
Ejemplo #1 Uso simple de array_key_first()
<?php
$array = ['a' => 1, 'b' => 2, 'c' => 3];
$firstKey = array_key_first($array);
var_dump($firstKey);
?>El ejemplo anterior mostrará:
string(1) "a"
Hay varias maneras de proporcionar esta funcionalidad para versiones anteriores a PHP 7.3.0. Es posible utilizar array_keys() , pero esto es bastante ineficiente. También es posible utilizar reset() y key() , pero esto puede cambiar el puntero interno del array. Una solución eficiente, que no modifica el puntero interno del array, escrita como un polyfill:
<?php
if (!function_exists('array_key_first')) {
function array_key_first(array $arr) {
foreach($arr as $key => $unused) {
return $key;
}
return NULL;
}
}
?>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));
?>