views:

85

answers:

4

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
}
+3  A: 

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.

Anti Veeranna
Looks interesting this PSL thing, will look at learning it soon.
Chris
+2  A: 

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
    }
}
?>
JP
+1  A: 

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.

Daniel Vandersluis
+1  A: 

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

Oliver