Page 1 of 1

find last iteration of a foreach loop on an array

Posted: Fri Aug 18, 2006 1:17 am
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

Posted: Fri Aug 18, 2006 1:47 am
by feyd
array_keys() and array_pop() in concert, live and unplugged. Image

Posted: Fri Aug 18, 2006 2:02 am
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 :)

Posted: Fri Aug 18, 2006 2:06 am
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.

Posted: Fri Aug 18, 2006 2:22 am
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.

Posted: Fri Aug 18, 2006 3:35 am
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