Last in array?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Cirdan
Forum Contributor
Posts: 144
Joined: Sat Nov 01, 2008 3:20 pm

Last in array?

Post by Cirdan »

When looping through an associative array, is there a way to find out if it's the last item in the array?
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Last in array?

Post 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.
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Last in array?

Post by Mark Baker »

Code: Select all

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