phpday 2027 - Call for Papers

array_key_first

(PHP 7 >= 7.3.0, PHP 8)

array_key_first — Restituisce la prima chiave di un array

Descrizione

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

Restituisce la prima chiave dell'array specificato senza influire sul puntatore interno dell'array.

Elenco dei parametri

array

Un array.

Valori restituiti

Restituisce la prima chiave di array se l'array non è vuoto; null altrimenti.

Esempi

Example #1 Utilizzo di base di array_key_first()

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

$firstKey = array_key_first($array);

var_dump($firstKey);
?>

Il precedente esempio visualizzerà:

string(1) "a"

Note

Suggerimento

Esistono diversi modi per fornire questa funzionalità nelle versioni precedenti a PHP 7.3.0. È possibile usare array_keys(), ma ciò può risultare piuttosto inefficiente. È anche possibile usare reset() e key(), ma ciò può modificare il puntatore interno dell'array. Una soluzione efficiente, che non modifica il puntatore interno dell'array, scritta come polyfill:

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

Vedere anche:

  • array_first() - Restituisce il primo valore di un array
  • array_key_last() - Restituisce l'ultima chiave di un array
  • reset() - Imposta il puntatore interno di un array al suo primo elemento
+add a note

User Contributed Notes 1 note

up
5
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));

?>
To Top