1

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?

0

5 Answers 5

6

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

3

First and last element of array:

foreach($array as $element) {
    if ($element === reset($array))
        echo 'FIRST ELEMENT!';

    if ($element === end($array))
        echo 'LAST ELEMENT!';
}

Comments

0

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?

Comments

0

that questions is confusing.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.