Question

I'm looping through an associative array with a foreach. I'd like to be able to check if the key value pair being handled is the last so I can give it special treatment. Any ideas how I can do this the best way?

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
}
Was it helpful?

Solution

Assuming you're not altering the array while iterating through it, you could maintain a counter that decrements in the loop and once it reaches 0, you're handling the last:

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

OTHER TIPS

Simple as this, free from counters and other 'hacks'.

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

   // your stuff

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

Please note that you have to use ===, because the function next() may return a non-boolean value which evaluates to false, such as 0 or "" (empty string).

we don't need to iterate through the array with foreach, we can use the end(), key() and current() php functions to get to the last element and get it's key + value.

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

?>

If you want to check it in the iteration, the end() function still can be useful:

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

There are quite a few ways to do that as other answers will no doubt show. But I would suggest to learn SPL and its CachingIterator. Here is an example:

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

It is more verbose than simple foreach, but not all that much. And all the different SPL iterators open up a whole new world for you, once you learn them :) Here is a nice tutorial.

You could use the array pointer traversal functions (specifically next) to determine if there is another element after the current one:

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

Note that this method won't work if your array contains elements whose value is FALSE, and you'll need to handle the last element after doing your usual loop body (because the array pointer is advanced by calling next) or else memoize the value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top