Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in foreach, isLastItem() exists?

Tags:

foreach

php

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?

like image 586
zmol Avatar asked Feb 09 '11 10:02

zmol


2 Answers

The valid() method says if the ArrayIterator object has more elements.

See:

$arr = array("Banana","Abacaxi","Abacate","Morango");

$iter = new ArrayIterator($arr);

while($iter->valid()){

    echo $iter->key()." - ".$iter->current()."<br/>";

    $iter->next();

}
like image 96
Paulo Luvisoto Avatar answered Oct 04 '22 00:10

Paulo Luvisoto


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
}
like image 41
awm Avatar answered Oct 04 '22 00:10

awm