PHP 8.3.4 Released!

array_key_first

(PHP 7 >= 7.3.0, PHP 8)

array_key_firstObtiene la primera clave de un array

Descripción

array_key_first(array $array): mixed

Consigue la primera clave del array dado sin afectar el puntero de array interno.

Parámetros

array

Un array;

Valores devueltos

Devuelve la primera clave del array si el array no está vacío; null en caso contrario.

Ejemplos

Ejemplo #1 Uso básico de array_key_first()

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

$firstKey = array_key_first($array);

var_dump($firstKey);
?>

El resultado del ejemplo sería:

string(1) "a"

Notas

Sugerencia

Hay varias maneras de proporcionar esta funcionalidad para las versiones anteriores a PHP 7.3.0. Es posible utilizar array_keys(), pero eso puede ser más bien ineficiente. También es posible utilizar reset() y key(), pero eso puede cambiar el puntero del array interno. Una solución eficiente, que no hace cambio del puntero del array interno, escrito como polietileno:

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

Ver también

  • array_key_last() - Obtiene la última clave de un array
  • reset() - Establece el puntero interno de un array a su primer elemento
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