Obtener la primera clave en una (posiblemente) matriz asociativa?


¿Cuál es la mejor manera de determinar la primera clave en una matriz posiblemente asociativa? Mi primer pensamiento que acaba de foreach la matriz y luego inmediatamente romperlo, así:

foreach ($an_array as $key => $val) break;

Por lo tanto, tener $key contiene la primera clave, pero esto parece ineficiente. ¿Alguien tiene una solución mejor?

 658
Author: Blixt, 2009-06-22

19 answers

Puede utilizar reset y key:

reset($array);
$first_key = key($array);

Es esencialmente el mismo que su código inicial, pero con un poco menos de sobrecarga, y es más obvio lo que está sucediendo.

Solo recuerde llamar a reset, o puede obtener cualquiera de las claves en la matriz. También puede utilizar end en lugar de reset para obtener la última tecla.

Si quieres que la clave obtenga el primer valor, reset realmente lo devuelve:

$first_value = reset($array);

Hay un caso especial para ver out for sin embargo (así que compruebe la longitud de la matriz primero):

$arr1 = array(false);
$arr2 = array();
var_dump(reset($arr1) === reset($arr2)); // bool(true)
 1163
Author: Blixt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-21 22:34:17

array_keys devuelve una matriz de claves. Toma la primera entrada. Alternativamente, puede llamar a reset en el array, y posteriormente a key. Este último enfoque es probablemente un poco más rápido (aunque no lo probé), pero tiene el efecto secundario de restablecer el puntero interno.

 66
Author: troelskn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-22 18:15:59

Curiosamente, el bucle foreach es en realidad la forma más eficiente de hacer esto.

Dado que el PO preguntó específicamente sobre la eficiencia, debe señalarse que todas las respuestas actuales son de hecho mucho menos eficientes que un foreach.

Hice un benchmark sobre esto con php 5.4, y el método reset/key pointer (respuesta aceptada) parece ser aproximadamente 7 veces más lento que un foreach. Otros enfoques que manipulan toda la matriz (array_keys, array_flip) son obviamente incluso más lento que eso y se vuelve mucho peor cuando se trabaja con una matriz grande.

Foreach no es ineficiente en absoluto, no dude en usarlo!

Editar 2015-03-03:

Se han solicitado scripts de Benchmark, no tengo los originales, pero hice algunas pruebas nuevas en su lugar. Esta vez encontré el foreach solo alrededor del doble de rápido que reset/key. Usé una matriz de 100 teclas y ejecuté cada método un millón de veces para obtener alguna diferencia notable, aquí está el código de la simple referencia:

$array = [];
for($i=0; $i < 100; $i++)
    $array["key$i"] = $i;

for($i=0, $start = microtime(true); $i < 1000000; $i++) {
    foreach ($array as $firstKey => $firstValue) {
        break;
    }
}
echo "foreach to get first key and value: " . (microtime(true) - $start) . " seconds <br />";

for($i=0, $start = microtime(true); $i < 1000000; $i++) {
    $firstValue = reset($array);
    $firstKey = key($array);
}
echo "reset+key to get first key and value: " . (microtime(true) - $start) . " seconds <br />";

for($i=0, $start = microtime(true); $i < 1000000; $i++) {
    reset($array);
    $firstKey = key($array);
}
echo "reset+key to get first key: " . (microtime(true) - $start) . " seconds <br />";


for($i=0, $start = microtime(true); $i < 1000000; $i++) {
    $firstKey = array_keys($array)[0];
}
echo "array_keys to get first key: " . (microtime(true) - $start) . " seconds <br />";

En mi php 5.5 esto produce:

foreach to get first key and value: 0.15501809120178 seconds 
reset+key to get first key and value: 0.29375791549683 seconds 
reset+key to get first key: 0.26421809196472 seconds 
array_keys to get first key: 10.059751987457 seconds

Restablecer+tecla http://3v4l.org/b4DrN/perf#tabs
foreach http://3v4l.org/gRoGD/perf#tabs

 48
Author: Webmut,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-03 15:06:50

key($an_array) te dará la primera tecla

Edit per Blixt: debe llamar a reset($array); antes de key($an_array) para restablecer el puntero al principio de la matriz.

 34
Author: jimyi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-22 18:35:25
list($firstKey) = array_keys($yourArray);
 21
Author: Sergiy Sokolenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-12 13:38:13

Si la eficiencia no es tan importante para usted, puede usar array_keys($yourArray)[0] en PHP 5.4 (y superior).

Ejemplos:

# 1
$arr = ["my" => "test", "is" => "best"];    
echo array_keys($arr)[0] . "\r\n"; // prints "my"


# 2
$arr = ["test", "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "0"

# 3
$arr = [1 => "test", 2 => "best"];
echo array_keys($arr)[0] . "\r\n"; // prints "1"

La ventaja sobre la solución:

list($firstKey) = array_keys($yourArray);

Es que puede pasar array_keys($arr)[0] como un parámetro de función (es decir, doSomething(array_keys($arr)[0], $otherParameter)).

HTH

 19
Author: Martin Vseticka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-28 06:56:19

Usted podría intentar

array_keys($data)[0]
 17
Author: Stopper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-28 10:07:26
$myArray = array(
    2 => '3th element',
    4 => 'first element',
    1 => 'second element',
    3 => '4th element'
);
echo min(array_keys($myArray)); // return 1
 11
Author: Hamidreza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-28 07:02:43

Por favor, encuentre lo siguiente:

$yourArray = array('first_key'=> 'First', 2, 3, 4, 5);
$keys   =   array_keys($yourArray);
echo "Key = ".$keys[0];

Creo que esto funcionará.

 9
Author: Pupil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-02 13:43:21

Esto también podría ser una solución.

$first_key = current(array_flip($array));

Lo he probado y funciona.

 8
Author: Pupil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-28 07:13:54
 $arr = array('key1'=>'value1','key2'=>'value2','key3'=>'key3');
 list($first_key) = each($arr);
 print $first_key;
 // key1
 3
Author: voodoo417,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-24 20:23:28

Para mejorar la solución de Webmut , he añadido la siguiente solución:

$firstKey = array_keys(array_slice($array, 0, 1, TRUE))[0];

La salida para mí en PHP 7.1 es:

foreach to get first key and value: 0.048566102981567 seconds 
reset+key to get first key and value: 0.11727809906006 seconds 
reset+key to get first key: 0.11707186698914 seconds 
array_keys to get first key: 0.53917098045349 seconds 
array_slice to get first key: 0.2494580745697 seconds 

Si hago esto para una matriz de tamaño 10000, entonces los resultados se convierten en

foreach to get first key and value: 0.048488140106201 seconds 
reset+key to get first key and value: 0.12659382820129 seconds 
reset+key to get first key: 0.12248802185059 seconds 
array_slice to get first key: 0.25442600250244 seconds 

El método array_keys se agota en 30 segundos (con solo 1000 elementos, el tiempo para el resto fue aproximadamente el mismo, pero el método array_keys tuvo aproximadamente 7.5 segundos).

 3
Author: PrinsEdje80,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-13 07:59:16

Para 2018 +

A partir de PHP 7.3, hay una función array_key_first() que logra exactamente esto:

$array = ['foo' => 'lorem', 'bar' => 'ipsum'];
$firstKey = array_key_first($array);
echo $firstKey; // 'foo'

La Documentación está disponible aquí.

 3
Author: Ivan Augusto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-29 13:50:15

La mejor manera que funcionó para mí fue

array_shift(array_keys($array))

array_keys obtiene la matriz de claves de la matriz inicial y luego array_shift corta el primer valor del elemento. Necesitará PHP 5.4+ para esto.

 2
Author: Yuriy Petrovskiy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-23 17:57:18

Esta es la manera más fácil que había encontrado. Rápido y solo dos líneas de código: - D

$keys = array_keys($array);
echo $array[$keys[0]];
 1
Author: Salvi Pascual,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-31 12:33:53

Una sola línea:

$array = array('key1'=>'value1','key2'=>'value2','key3'=>'key3');
echo key( array_slice( $array, 0, 1, true ) );

# echos 'key1'
 0
Author: Kohjah Breese,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-06 12:44:13

Hoy tuve que buscar la primera clave de mi matriz devuelta por una solicitud POST. (Y anote el número para un id de formulario, etc.)

Bueno, he encontrado esto: Devuelve la primera clave del array asociativo en PHP

Http://php.net/key

He hecho esto, y funciona.

    $data = $request->request->all();
    dump($data);
    while ($test = current($data)) {
        dump($test);
        echo key($data).'<br />';die();
        break;
    }

Tal vez sea eco 15min de otro tipo. CYA.

 0
Author: Roupioz Clement,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-20 13:46:53

Una versión más universal y segura con respaldo para un iterable / array vacío:

Nota: Asumiendo que el array $es un array o iterable (PHP >=7.1)

$array = [/* ... */]; // my array or iterable

// these lines are a fallback for the case nothing is found
$firstKey = null; // null or default value of your choice
$firstValue = null; // null or default value of your choice

// iterating the array
foreach ($array as $firstKey => $firstValue) {
    // stop after first iteration
    break;
}

TLDR: De esta manera no es necesario volver a comprobar el iterable. (array en este caso).

Foreach es la forma más rápida de iterar sobre todo.

Recomendaciones y explicaciones: Recomiendo establecer valores predeterminados para $firstKey y $firstValue antes de iterar, solo para saber si la matriz estaba vacía o ni.

Nota: Si confía en que su matriz siempre estará poblada, no hay necesidad de valores predeterminados. (pero 100% seguro de eso!)

Explicación para cosas más avanzadas:

Si el iterable tiene un Iterator personalizado, es posible que deba restablecerlo manualmente después de la instrucción foreach.

Más sobre PHP: iterables

 -1
Author: Gabi Dj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-01 15:04:25

Puedes jugar con tu array

$daysArray = array('Monday', 'Tuesday', 'Sunday');
$day = current($transport); // $day = 'Monday';
$day = next($transport);    // $day = 'Tuesday';
$day = current($transport); // $day = 'Tuesday';
$day = prev($transport);    // $day = 'Monday';
$day = end($transport);     // $day = 'Sunday';
$day = current($transport); // $day = 'Sunday';

Para obtener el primer elemento del array puedes usar current y para el último elemento puedes usar end

Editar

Solo por no obtener más votos negativos para la respuesta, puede convertir su clave en valor usando array_keys y usar como se muestra arriba.

 -1
Author: Priyank,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-23 06:27:08