In foreach, isLastItem () exists?

Using a regular loop, it can compose the current index with the last to find out if I am 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 find out the current index of the current iteration, for example $iteration = 5 , so I can manually compare it with the length of $array ?

+8
php foreach
source share
8 answers

You can use a combination of the SPL ArrayIterator and the CachingIterator class to have a hasNext method :

 $iter = new CachingIterator(new ArrayIterator($arr)); foreach ($iter as $value) { $last_iteration = !$iter->hasNext(); } 
+11
source share

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 } 
+21
source share

No, you need to have a counter and know the number of items in the list. You can use end() to get the last element in the array and see if it matches the current value in foreach .

+1
source share

If you know that the array values ​​will always be unique, you can compare the current $item with end($array) to see if you still have the last element. Otherwise, no, you need a counter.

+1
source share

You can get the key and value in foreach() as follows:

foreach($array as $key=>$value) { ... }

Alternatively, you can do the count() array so that you know how many elements it has and have an increment counter so that you know when you reach the last element.

+1
source share
 end($array); $lastKey = key($array); foreach($array as $key => $value) { if ($key === $lastKey) { // do something endish } } 
+1
source share

Here are some ways to do this:

 $items = ["Bhir", "Ekky", null, "Uych", "foo"=>"bar"]; $values = array_values($items); // Bhir, Ekky, Uych, bar foreach ($values as $i => $item) { print("$item"); $next = isset($values[$i + 1]); if ($next) { print(", "); } } // Bhir, Ekky, , Uych, bar foreach ($values as $i => $item) { print("$item"); $next = array_key_exists($i + 1, $values); if ($next) { print(", "); } } // Bhir, Ekky, , Uych, bar $i = count($values); foreach ($items as $item) { print("$item"); $next = !!(--$i); if ($next) { print(", "); } } // Bhir, Ekky, , Uych, bar $items = new \CachingIterator(new \ArrayIterator($items)); foreach ($items as $item) { print("$item"); $next = $items->hasNext(); if ($next) { print(", "); } } 
+1
source share

The valid () method indicates whether the ArrayIterator has more elements.

Cm:

 $arr = array("Banana","Abacaxi","Abacate","Morango"); $iter = new ArrayIterator($arr); while($iter->valid()){ echo $iter->key()." - ".$iter->current()."<br/>"; $iter->next(); } 
0
source share

All Articles