Domanda

Sto attraversando un array associativo con un foreach. Mi piacerebbe essere in grado di verificare se la coppia chiave-valore gestita è l'ultima in modo da poterle dare un trattamento speciale. Qualche idea su come posso farlo nel modo migliore?

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
}
È stato utile?

Soluzione

Supponendo che non si stia alterando l'array mentre si scorre attraverso di esso, è possibile mantenere un contatore che diminuisce nel ciclo e una volta che raggiunge 0, si sta gestendo l'ultimo:

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

Altri suggerimenti

Semplice come questo, privo di contatori e altri "hack".

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

   // your stuff

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

Nota che devi usare === , perché la funzione next () può restituire un valore non booleano che viene valutato in false , come 0 o " " (stringa vuota).

non abbiamo bisogno di iterare l'array con foreach, possiamo usare le funzioni php end (), key () e current () per arrivare all'ultimo elemento e ottenere la sua chiave + valore.

<?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";

?>

Se vuoi controllarlo nell'iterazione, la funzione end () può ancora essere utile:

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

Ci sono molti modi per farlo, come dimostreranno senza dubbio altre risposte. Ma suggerirei di imparare SPL e i suoi CachingIterator . Ecco un esempio:

<?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";
    }
}

È più prolisso che semplice foreach, ma non così tanto. E tutti i diversi iteratori SPL ti aprono un mondo completamente nuovo, una volta che li impari :) Ecco un bel tutorial.

È possibile utilizzare le funzioni di attraversamento del puntatore di array (in particolare next ) per determinare se esiste un altro elemento dopo quello corrente:

$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)

Nota che questo metodo non funzionerà se l'array contiene elementi il ??cui valore è FALSE e dovrai gestire l'ultimo elemento dopo aver eseguito il consueto corpo del ciclo (poiché il puntatore dell'array è avanzato chiamando next ) oppure memoize il valore.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top