CakeFest 2024: The Official CakePHP Conference

array_key_first

(PHP 7 >= 7.3.0, PHP 8)

array_key_firstObtém a primeira chave de um array

Descrição

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

Obtenha a primeira chave do array fornecido sem afetar o ponteiro do array interno.

Parâmetros

array

Um array.

Valor Retornado

Retorna a primeira key do array se o array não estiver vazio; null caso contrário.

Exemplos

Exemplo #1 Uso básico de array_key_first()

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

$firstKey = array_key_first($array);

var_dump($firstKey);
?>

O exemplo acima produzirá:

string(1) "a"

Notas

Dica

Existem várias maneiras de fornecer essa funcionalidade para versões anteriores ao PHP 7.3.0. É possível usar array_keys(), mas isso pode ser bastante ineficiente. Também é possível usar reset() e key(), mas isso pode alterar o ponteiro do array interno. Uma solução eficiente, que não altera o ponteiro interno do array, escrito como polyfill:

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

Veja Também

  • array_key_last() - Obtém a última chave de um array
  • reset() - Faz o ponteiro interno de um array apontar para o seu primeiro 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