Say I have a foreach
loop.
I have to do something with the first object of the loop that I don't have to do with any of the other objects.
How do I check if the item that's currently in the loop is the first object.
forEach() , and it will definitely iterate over array elements in ascending index order (skipping indices that were never assigned a value).
Luckily, there are several ways to get an index variable with foreach : Declare an integer variable before the loop, and then increase that one inside the loop with each loop cycle. Create a tuple that returns both the element's value and its index. Or swap the foreach loop with the for loop.
The foreach loop is mainly used for looping through the values of an array. It loops over the array, and each value for the current array element is assigned to $value, and the array pointer is advanced by one to go the next element in the array. Syntax: <?
The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
I like the Linq way, but without the Skip(1), this way you can also use it for the last item in a list and your code remains clean imho :)
foreach(var item in items) { if (items.First()==item) item.firstStuff(); else if (items.Last() == item) item.lastStuff(); item.otherStuff(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With