(PHP 4, PHP 5, PHP 7, PHP 8)
key — Devuelve una clave de un array asociativo
key() devuelve la clave actual en el
array array
.
array
El array.
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
.
Versión | Descripción |
---|---|
8.1.0 | Calling this function on objets is deprecated. Either convert the objet to an tableau 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. |
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