Page 1 of 1

Last in array?

Posted: Sun Aug 23, 2009 4:09 pm
by Cirdan
When looping through an associative array, is there a way to find out if it's the last item in the array?

Re: Last in array?

Posted: Sun Aug 23, 2009 4:21 pm
by jackpf
Increment a counter throughout, then check if it's equal to count($the_array) - 1. Remember, count() starts from 1...so you have to subtract 1.

Re: Last in array?

Posted: Sun Aug 23, 2009 4:34 pm
by Mark Baker

Code: Select all

 
$lastkey = end(array_keys($arr));
foreach ($arr as $key => $value) {
    if ($key == $lastkey) {
      ...
   }
}