Cómo encontrar el índice foreach


¿Es posible encontrar el índice foreach?

En un bucle for como sigue:

for ($i = 0; $i < 10; ++$i) {
   echo $i . ' ';
}

$i te dará el índice.

¿Tengo que usar el bucle for o hay alguna manera de obtener el índice en el bucle foreach?

Author: buræquete, 2008-09-26

12 answers

foreach($array as $key=>$value) {
    // do stuff
}

$key es el índice de cada elemento $array

 693
Author: Owen,
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-05-15 19:24:45

Puede poner un hack en su foreach, como un campo incrementado en cada ejecución, que es exactamente lo que el bucle for le da en una matriz indexada numéricamente. Tal campo sería un pseudo-índice que necesita gestión manual (incrementos, etc.).

A foreach le dará su índice en forma de su valor $key, por lo que tal hack no debería ser necesario.

Por ejemplo, en un foreach

$index = 0;
foreach($data as $key=>$val) {
    // Use $key as an index, or...

    // ... manage the index this way..
    echo "Index is $index\n";
    $index++;
}
 134
Author: ConroyP,
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-12-14 03:16:36

Cabe señalar que se puede llamar key() en cualquier matriz a encontrar la clave actual de su sobre. Como puede adivinar, current() devolverá el valor actual y next() moverá el puntero del array al siguiente elemento.

 22
Author: Bailey Parker,
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-03-04 11:17:22

Owen tiene una buena respuesta. Si desea solo la clave, y está trabajando con una matriz, esto también podría ser útil.

foreach(array_keys($array) as $key) {
//  do stuff
}
 14
Author: Zoredache,
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
2008-09-26 21:35:43

Puede crear $i fuera del bucle y hacer $i++ en la parte inferior del bucle.

 11
Author: Ólafur Waage,
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-08-19 11:20:40

Estos dos bucles son equivalentes (bar las barandas de seguridad, por supuesto):

for ($i=0; $i<count($things); $i++) { ... }

foreach ($things as $i=>$thing) { ... }

Eg

for ($i=0; $i<count($things); $i++) {
    echo "Thing ".$i." is ".$things[$i];
}

foreach ($things as $i=>$thing) {
    echo "Thing ".$i." is ".$thing;
}
 7
Author: Trev,
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-12-14 03:16:53

Los arrays PHP tienen punteros internos, así que prueba esto:

foreach($array as $key => $value){
   $index = current($array);
}

Funciona bien para mí (aunque solo se probó muy preliminarmente).

 5
Author: sth,
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
2010-12-29 04:35:32

Jonathan tiene razón. Los arrays PHP actúan como una tabla de mapas que asigna claves a valores. en algunos casos puede obtener un índice si su matriz está definida, como

$var = array(2,5);

for ($i = 0; $i < count($var); $i++) {
    echo $var[$i]."\n";
}

Su salida será

2
5

En cuyo caso cada elemento en la matriz tiene un índice conocible, pero si luego haces algo como lo siguiente

$var = array_push($var,10);

for ($i = 0; $i < count($var); $i++) {
    echo $var[$i]."\n";
}

No obtienes salida. Esto sucede porque los arrays en PHP no son estructuras lineales como lo son en la mayoría de los lenguajes. Son más como tablas hash que pueden o puede no tener claves para todos los valores almacenados. Por lo tanto, foreach no usa índices para rastrearlos porque solo tienen un índice si el array está definido. Si necesita tener un índice, asegúrese de que sus matrices estén completamente definidas antes de arrastrarse sobre ellas, y use un bucle for.

 4
Author: The Brawny Man,
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
2008-09-26 18:47:18

Creo que la mejor opción es igual:

foreach ($lists as $key=>$value) {
    echo $key+1;
}

Es fácil y normalmente

 2
Author: Mikel Williams,
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-12-14 03:17:21

Normalmente hago esto cuando trabajo con matrices asociativas:

foreach ($assoc_array as $key => $value) {
 //do something
}

Esto también funcionará bien con matrices no asociativas. key key será el valor del índice. Si lo prefiere, puede hacer esto también:

foreach ($array as $indx => $value) {
  //do something
}
 1
Author: Randy Greencorn,
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-12-14 03:17:07
foreach(array_keys($array) as $key) {
//  do stuff
}
 0
Author: gdmanandamohon,
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-06-16 10:12:58
foreach($arrvariable as $key=>$value){
echo "$key";
}
 -4
Author: Senthil Kumar,
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-09-20 13:22:42