Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Using a regular for loop, it's possible to comapred the current index with the last to tell if I'm in the last iteration of the loop. Is there a similar thing when using foreach? I mean something like this.

foreach($array as $item){
  //do stuff
  //then check if we're in the last iteration of the loop
  $last_iteration = islast(); //boolean true/false
}

If not, is there at least a way to know the current index of the current iteration like $iteration = 5, so I can manually compare it to the length of the $array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
226 views
Welcome To Ask or Share your Answers For Others

1 Answer

The counter method is probably the easiest.

$i = count($array);
foreach($array as $item){
  //do stuff
  //then check if we're in the last iteration of the loop
  $last_iteration = !(--$i); //boolean true/false
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...