key

(PHP 4, PHP 5, PHP 7, PHP 8)

keyDevuelve una clave de un array asociativo

Descripción

key(array|object $array): int|string|null

key() devuelve la clave actual en el array array.

Parámetros

array

El array.

Valores devueltos

La función key() devuelve simplemente la clave del elemento del array que es actualmente apuntado por el puntero interno. Esta función no modifica en ningún caso la posición de este puntero. Si el puntero interno apunta un elemento situado después del final de la lista de elementos, o bien si el array está vacío, la función key() devolverá null.

Historial de cambios

Versión Descripción
8.1.0 Calling this function on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead.
7.4.0 Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function.

Ejemplos

Ejemplo #1 Ejemplo con key()

<?php
$array
= array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');

// Este ciclo muestra todas las claves
// cuyo valor es "apple"
while ($fruit_name = current($array)) {
if (
$fruit_name == 'apple') {
echo
key($array), "\n";
}
next($array);
}
?>

El resultado del ejemplo sería:

fruit1
fruit4
fruit5

Ver también