PHP: array_key_first - Manual

(PHP 7 >= 7.3.0, PHP 8)

array_key_firstRecupera la primera clave de un array

Descripción

Parámetros

array

Un array.

Valores devueltos

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

Ejemplos

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á:

Notas

Sugerencia

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

Ver también

Found A Problem?

MaxiCom dot Developpement at gmail dot com

2 years 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));

?>