find last iteration of a foreach loop on an 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
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

find last iteration of a foreach loop on an array

Post by Stryks »

Hey all,

This seems like such a newb question but I'm looking through some old code and I cant believe I came to doing something the way I did ... and what's worse, I cant seem to see a better way.

I generate an array with a list of values, which print_r shows as:

Code: Select all

array( [32]=> Small [34]=> Medium [46]=> Large )
When setting the array (from a database) I just set each index to a variable called size_last so that the last one added is marked as the last in the array (the query returns the values with keys sorted).

Then later on, in order to find the last one, I just do:

Code: Select all

foreach($size_list as $key=>$size_name){
   if($key == $size_last) ... do suff
}
Seems pretty messy, but I cant seem to find a way to tell it to do something different on the final run through. Surely there is a built-in function for this somewhere.

Any tips would be great. Cheers
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

array_keys() and array_pop() in concert, live and unplugged. Image
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

Ok ... I'll bite

Having looked now, I can see using array_keys() to get the result I'm hoping for.

But how would array_pop apply? :?

Thanks for the reply though :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

$arr = array( 32=> 'Small', 34=> 'Medium', 46=> 'Large' );

$keys = array_keys($arr);
var_dump($keys);
$lastKey = array_pop($keys);
var_dump($keys, $lastKey);
A real question could be, why do you need to find the last iteration? Why not do that code after the loop ends and save yourself some processing time avoiding if() throughout.
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Post by Stryks »

Well .. it's just to apply formatting to a cell, thats all.

A row of sizes applying to one item, and the last one gets tagged with a css class to give it a border.

There may be a better way to do this, but this is just the way I did it.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

as a note, when using a foreach() loop you can use the variables after the loop as well..

Code: Select all

foreach ($array as $key => $val) {
// do something
}

//$key and $val now contain the last iteration of the loop
Post Reply