PHP Conference Kansai 2025

array_key_first

(PHP 7 >= 7.3.0, PHP 8)

array_key_firstRecupera la primera clave de un array

Descripción

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

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

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 resultado del ejemplo sería:

string(1) "a"

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

  • array_key_last() - Recupera la última clave de un array
  • reset() - Reinicia el puntero interno del array al principio
add a note

User Contributed Notes 1 note

up
2
MaxiCom dot Developpement at gmail dot com
1 year 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));

?>
To Top

Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant