(PHP 7 >= 7.3.0, PHP 8)
array_key_first — Récupère la première clé d'un tableau
Récupère la première clé du tableau array
donné sans
affecter le pointeur interne du tableau.
array
Un tableau.
Retourne la première clé de array
si le tableau n'est pas
vide ; null
sinon.
Exemple #1 Usage simple de array_key_first()
<?php
$array = ['a' => 1, 'b' => 2, 'c' => 3];
$firstKey = array_key_first($array);
var_dump($firstKey);
?>
L'exemple ci-dessus va afficher :
string(1) "a"
Il y a plusieurs façon de fournir cette fonctionnalité pour les versions antérieur à PHP 7.3.0. Il est possible d'utiliser array_keys() , mais ceci est plutôt inefficace. Il est aussi possible d'utiliser reset() et key() , mais ceci peut changer le pointeur interne du tableau. Une solution efficace, qui ne modifie pas le pointeur interne du tableau, écrit comme 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));
?>