Pregunta

Estoy recorriendo una matriz asociativa con un foreach. Me gustaría poder verificar si el par de valores clave que se maneja es el último para poder darle un tratamiento especial. ¿Alguna idea de cómo puedo hacer esto de la mejor manera?

foreach ($kvarr as $key => $value){
   // I'd like to be able to check here if this key value pair is the last
   // so I can give it special treatment
}
¿Fue útil?

Solución

Suponiendo que no está alterando la matriz mientras itera a través de ella, podría mantener un contador que disminuye en el ciclo y una vez que llega a 0, está manejando el último:

<?php
$counter = count($kvarr);
foreach ($kvarr as $key => $value)
{
    --$counter;
    if (!$counter)
    {
        // deal with the last element
    }
}
?>

Otros consejos

Tan simple como esto, libre de contadores y otros 'hacks'.

foreach ($array as $key => $value) {

   // your stuff

   if (next($array) === false) {
      // this is the last iteration
   }
}

Tenga en cuenta que debe usar === , porque la función next () puede devolver un valor no booleano que evalúa como falso , como 0 o " " (cadena vacía).

no necesitamos iterar a través de la matriz con foreach, podemos usar las funciones php end (), key () y current () para llegar al último elemento y obtener su clave + valor.

<?php

$a = Array(
  "fruit" => "apple",
  "car" => "camaro",
  "computer" => "commodore"
);

// --- go to the last element of the array & get the key + value --- 
end($a); 
$key = key($a);
$value = current($a);

echo "Last item: ".$key." => ".$value."\n";

?>

Si desea verificarlo en la iteración, la función end () aún puede ser útil:

foreach ($a as $key => $value) {
    if ($value == end($a)) {
      // this is the last element
    }
}

Hay bastantes maneras de hacerlo, como sin duda mostrarán otras respuestas. Pero sugeriría aprender SPL y su CachingIterator . Aquí hay un ejemplo:

<?php

$array = array('first', 'second', 'third');

$object = new CachingIterator(new ArrayIterator($array));
foreach($object as $value) {
    print $value;

    if (!$object->hasNext()) {
        print "<-- that was the last one";
    }
}

Es más detallado que simple foreach, pero no tanto. Y todos los diferentes iteradores SPL te abren un mundo completamente nuevo, una vez que los aprendes :) Aquí hay un buen tutorial.

Puede usar las funciones de recorrido del puntero de matriz (específicamente siguiente ) para determinar si hay otro elemento después del actual:

$value = reset($kvarr);
do
{
  $key = key($kvarr);
  // Do stuff

  if (($value = next($kvarr)) === FALSE)
  {
    // There is no next element, so this is the last one.
  }
}
while ($value !== FALSE)

Tenga en cuenta que este método no funcionará si su matriz contiene elementos cuyo valor es FALSE , y necesitará manejar el último elemento después de hacer su cuerpo de bucle habitual (porque el puntero de la matriz es avance llamando a next ) o bien memorice el valor.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top