PHP 8.3.4 Released!

array_key_first

(PHP 7 >= 7.3.0, PHP 8)

array_key_firstRécupère la première clé d'un tableau

Description

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

Récupère la première clé du tableau array donné sans affecter le pointeur interne du tableau.

Liste de paramètres

array

Un tableau.

Valeurs de retour

Retourne la première clé de array si le tableau n'est pas vide ; null sinon.

Exemples

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"

Notes

Astuce

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;
}
}
?>

Voir aussi

  • array_key_last() - Récupère la dernière clé d'un tableau
  • reset() - Remet le pointeur interne de tableau au début
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