views:

711

answers:

3

Ok I have a foreach loop and wanted to know if I could get the last iteration data value for the current iteration?

Code:

foreach($array as $key=>$data) {
   echo "Key: ".$key." Data: ".$data."<br />";
}

Results:

Key: 0 Data: 23244
Key: 0 Data: Program ID: 39-1-1499-1

Results I would like:

Key: 23244 Data: Program ID: 39-1-1499-1

is there a way to get the key on the current iteration as the data from the last?

+4  A: 
$i=0;
foreach($array as $key=>$data) {
   if($i%2 == 0){ echo "Key: ".$data;}
   else{ echo "Data: ".$data."<br />";}
   $i++;
}

Or something to that effect should work.

It's worth noting though, that it's probably better to fix the source of the issue (the array) so that it outputs in the correct format and you can use your original code rather than this workaround.

munch
thnx, worked but you have a typo
Phill Pafford
A: 

You probably don't want to do this with a foreach loop but with function calls. I don't fully understand your data structure because the key 0 seems to have two different values assigned, could you please explain it in more detail?

Otto Allmendinger
it's a multi dem array
Phill Pafford
+4  A: 

i'm not sure i understand yr question very well.. but looks like you need the last item in the array...there are ways to get the first/last items from an array without having to iterate over them.

$last_item = end($array);

have a look at the php manual for examples..

Yash