Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch forEach last iteration

arr = [1,2,3]; arr.forEach(function(i){ // last iteration }); 

How to catch when the loop ending? I can do if(i == 3) but I might don't know what is the number of my array.

like image 740
Jamie Anderson Avatar asked Apr 20 '15 02:04

Jamie Anderson


People also ask

How do I find my last foreach iteration?

Use count() to determine the total length of an array. The iteration of the counter was placed at the bottom of the foreach() loop - $x++; to execute the condition to get the first item. To get the last item, check if the $x is equal to the total length of the array. If true , then it gets the last item.

How to get last value from loop in PHP?

The last value is still available after the loop, so if you just want to use it for more stuff after the loop this is better: foreach($arr as $key=>$value) { //something } echo "last index! $key => $value"; If you do not want to treat the last value as special inside loops.

Does foreach wait for completion?

Because forEach does not wait for each promise to resolve, all the prizes are awarded in parallel, not serial (one by one). So the loop actually finishes iterating before any of the prizes have finished been awarded (but after they have all started being awarded).


1 Answers

Updated answer for ES6+ is here.


arr = [1, 2, 3];   arr.forEach(function(i, idx, array){    if (idx === array.length - 1){         console.log("Last callback call at index " + idx + " with value " + i );     } }); 

would output:

Last callback call at index 2 with value 3 

The way this works is testing arr.length against the current index of the array, passed to the callback function.

like image 190
jdphenix Avatar answered Oct 21 '22 07:10

jdphenix