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
Find the last element of an array while using a foreach loop in PHP
It sounds like you want something like this:
$numItems = count($arr);
$i = 0;
foreach($arr as $key=>$value) {
if(++$i === $numItems) {
echo "last index!";
}
}
That being said, you don't -have- to iterate over an "array" using foreach
in php.
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++;
}
Find last iteration of foreach loop in laravel blade
As for Laravel 5.3+, you can use the $loop variable
$loop->last
@foreach ($colors as $k => $v)
@if($loop->last)
// at last loop, code here
@endif
@endforeach
How do you find the last loop in a For Each (VB.NET)?
The generally, collections on which you can perform For Each
on implement the IEnumerator
interface. This interface has only two methods, MoveNext
and Reset
and one property, Current
.
Basically, when you use a For Each
on a collection, it calls the MoveNext
function and reads the value returned. If the value returned is True
, it means there is a valid element in the collection and element is returned via the Current
property. If there are no more elements in the collection, the MoveNext
function returns False
and the iteration is exited.
From the above explanation, it is clear that the For Each
does not track the current position in the collection and so the answer to your question is a short No.
If, however, you still desire to know if you're on the last element in your collection, you can try the following code. It checks (using LINQ) if the current item is the last item.
For Each item in Collection
If item Is Collection.Last Then
'do something with your last item'
End If
Next
It is important to know that calling Last()
on a collection will enumerate the entire collection. It is therefore not recommended to call Last()
on the following types of collections:
- Streaming collections
- Computationally expensive collections
- Collections with high tendency for mutation
For such collections, it is better to get an enumerator for the collection (via the GetEnumerator()
function) so you can keep track of the items yourself. Below is a sample implementation via an extension method that yields the index of the item, as well as whether the current item is the first or last item in the collection.
<Extension()>
Public Iterator Function EnumerateEx(Of T)(collection As IEnumerable(Of T))
As IEnumerable(Of (value As T, index As Integer, isFirst As Boolean, isLast As Boolean))
Using e = collection.GetEnumerator()
Dim index = -1
Dim toYield As T
If e.MoveNext() Then
index += 1
toYield = e.Current
End If
While e.MoveNext()
Yield (toYield, index, index = 0, False)
index += 1
toYield = e.Current
End While
Yield (toYield, index, index = 0, True)
End Using
End Function
Here is a sample usage:
Sub Main()
Console.WriteLine("Index Value IsFirst IsLast")
Console.WriteLine("----- ----- ------- ------")
Dim fibonacci = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89}
For Each i In fibonacci.EnumerateEx()
Console.WriteLine(String.Join(" ", $"{i.index,5}",
$"{i.value,5}",
$"{i.isFirst,-7}",
$"{i.isLast,-6}"))
Next
Console.ReadLine()
End Sub
Output
Index Value IsFirst IsLast
----- ----- ------- ------
0 0 True False
1 1 False False
2 1 False False
3 2 False False
4 3 False False
5 5 False False
6 8 False False
7 13 False False
8 21 False False
9 34 False False
10 55 False False
11 89 False True
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
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
}
}
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
Parameters Passed by Reference Come Back Garbage Using P/Invoke
Capture Stored Procedure Print Output in .Net
Generics in C#, Using Type of a Variable as Parameter
When to Use Ref and When It Is Not Necessary in C#
Make Https Call Using Httpclient
Parallel.Foreach and Async-Await
Generating an Xml Serialization Assembly as Part of My Build
Restarting (Recycling) an Application Pool
Find an Item in a List by Linq
How to Pass a Value from a Child Back to the Parent Form
How to Autheticate to Ibm Mq C# with Tls-Certificate
Casting Interfaces for Deserialization in JSON.Net
How to Find All Combinations of Items in an Array
Cross-Thread Operation Not Valid