Foreach Loop, Determine Which Is the Last Iteration of the Loop

PHP How to determine the first and last iteration in a foreach loop?

You could use a counter:

$i = 0;
$len = count($array);
foreach ($array as $item) {
if ($i == 0) {
// first
} else if ($i == $len - 1) {
// last
}
// …
$i++;
}

Foreach loop, determine which is the last iteration of the loop

If you just need to do something with the last element (as opposed to something different with the last element then using LINQ will help here:

Item last = Model.Results.Last();
// do something with last

If you need to do something different with the last element then you'd need something like:

Item last = Model.Results.Last();
foreach (Item result in Model.Results)
{
// do something with each item
if (result.Equals(last))
{
// do something different with the last item
}
else
{
// do something different with every item but the last
}
}

Though you'd probably need to write a custom comparer to ensure that you could tell that the item was the same as the item returned by Last().

This approach should be used with caution as Last may well have to iterate through the collection. While this might not be a problem for small collections, if it gets large it could have performance implications. It will also fail if the list contains duplicate items. In this cases something like this may be more appropriate:

int totalCount = result.Count();
for (int count = 0; count < totalCount; count++)
{
Item result = Model.Results[count];

// do something with each item
if ((count + 1) == totalCount)
{
// do something different with the last item
}
else
{
// do something different with every item but the last
}
}

detect last foreach loop iteration

There isn't, take a look at How does the Java 'for each' loop work?

You must change your loop to use an iterator explicitly or an int counter.

Foreach loop, determine which is the last iteration of the loop - DataRow

You can simply write

 DataRow last = dsRequests.Tables["Requests"].AsEnumerable().LastOrDefault();
if(last != null)
.....

forcing the DataTable to be enumerable then you can use LastOrDefault(). Notice that I am using LastOrDefault because, if the table is empty, Last() will get you an exception.

Another approach is through the old fashioned index over the Rows collection

    DataRow last = null;
int idx = dsRequests.Tables["Requests"].Rows.Count;
if(idx > 0) last = dsRequests.Tables["Requests"].Rows[idx -1];
if(last != null)
....

In this example you have to test the number of rows after getting the count.

I should also add that the last example using the index to access the last row is more performant. However my tests show that on a 100000 loop the difference is simply 40 millisecs. Nothing to worry about.

C# how to determine the last iteration of foreach loop

All you need to do is move the second if. You dont want to override the longest gap everytime, only if you know it is definitely between two 1's.

if (Z == '0')
{
gap++;
}
else // if (Z == '1')
{
if (gap > longestgap)
{
longestgap = gap;
}

gap = 0;
}

This way, even if the gap keeps counting up until the end of your binary, if you don't find a second '1', the longest gap will still be 0.

Identifying last loop when using for each

How about obtaining a reference to the last item first and then use it for comparison inside the foreach loop? I am not say that you should do this as I myself would use the index based loop as mentioned by KlauseMeier. And sorry I don't know Ruby so the following sample is in C#! Hope u dont mind :-)

string lastItem = list[list.Count - 1];
foreach (string item in list) {
if (item != lastItem)
Console.WriteLine("Looping: " + item);
else Console.Writeline("Lastone: " + item);
}

I revised the following code to compare by reference not value (can only use reference types not value types). the following code should support multiple objects containing same string (but not same string object) since MattChurcy's example did not specify that the strings must be distinct and I used LINQ Last method instead of calculating the index.

string lastItem = list.Last();
foreach (string item in list) {
if (!object.ReferenceEquals(item, lastItem))
Console.WriteLine("Looping: " + item);
else Console.WriteLine("Lastone: " + item);
}

Limitations of the above code. (1) It can only work for strings or reference types not value types. (2) Same object can only appear once in the list. You can have different objects containing the same content. Literal strings cannot be used repeatedly since C# does not create a unique object for strings that have the same content.

And i no stupid. I know an index based loop is the one to use. I already said so when i first posted the initial answer. I provided the best answer I can in the context of the question. I am too tired to keep explaining this so can you all just vote to delete my answer. I'll be so happy if this one goes away. thanks

Last iteration in foreach loop with Object Javascript

You could use index and array parameters to check if there is next element. You can also check if current index is equal length - 1 index == arr.length - 1

let objName = { item1 : "someItem", item2 : "someItem", item3 : "someItem",}
Object.keys(objName).forEach((item, index, arr) => { console.log(item); if(!arr[index + 1]) console.log('End')});

catch forEach last iteration

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.

laravel check last iteration of foreach loop while using if condition in the foreach loop

You can use $loop->last :

@foreach($cuisines as $cuisine)
@if(($cuisine->id)==($scuitem->cuisine_id))
{{ $cuisine->title }}
@if(!($loop->last))

@endif
@endif
@endforeach

Edited :

Now Use this code in Controller and pass $str to view

$arr = [];
foreach($cuisines as $cuisine){
if(($cuisine->id)==($scuitem->cuisine_id)){
$arr[] = $cuisine->title;
}
}
$str = implode(' • ',$arr);

Or if you want to code in view than use as below :

@php
$arr = [];
foreach($cuisines as $cuisine){
if(($cuisine->id)==($scuitem->cuisine_id)){
$arr[] = $cuisine->title;
}
}
$str = implode(' • ',$arr);
@endphp


Related Topics



Leave a reply



Submit