简体   繁体   中英

PHP get last iteration foreach loop value

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?

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

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

First and last element of array:

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

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

that questions is confusing.

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM