Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

4 Answers

up vote 5 down vote accepted
$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.

share|improve this answer
thnx, worked but you have a typo – Phill Pafford Feb 15 '10 at 19:10

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..

share|improve this answer

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?

share|improve this answer
it's a multi dem array – Phill Pafford Feb 15 '10 at 19:01

that questions is confusing.

in foreach() loops, the last iteration values are still in your $key and $data vars, until they are changed.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.