How to Find the Foreach Index

How do you get the index of the current iteration of a foreach loop?

The foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.

This Enumerator has a method and a property:

  • MoveNext()
  • Current

Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.

The concept of an index is foreign to the concept of enumeration, and cannot be done.

Because of that, most collections are able to be traversed using an indexer and the for loop construct.

I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.

How to find the foreach index?

foreach($array as $key=>$value) {
// do stuff
}

$key is the index of each $array element

Get current index from foreach loop

IEnumerable list = DataGridDetail.ItemsSource as IEnumerable;
List<string> lstFile = new List<string>();

int i = 0;
foreach (var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row)).IsChecked;
if (IsChecked)
{
MessageBox.show(i);
--Here i want to get the index or current row from the list

}
++i;
}

How can i get index use forEach loop?

You can simply use a for loop and use classList.contains() to check if the class is present. Also, you need to declare a local var, to store the index returned from the loop.

const product = document.querySelector(".product");
const productList = product.querySelectorAll("li");

function getIdx() {
let idx;
for (var i = 0; i < productList.length; i++) {
let list = productList[i];

if (list.classList.contains("on")) {
idx = i;
}
}
return idx;
};

function printIdx() {
let idx = getIdx();

console.log(idx);
}

productList.forEach(list => {
list.addEventListener("click", printIdx);
});
<ul class="product">
<li>aaaaa</li>
<li>bbbbb</li>
<li class="on">ccccc</li>
<li>ddddd</li>
</ul>

Get index in ForEach in SwiftUI

This works for me:

Using Range and Count

struct ContentView: View {
@State private var array = [1, 1, 2]

func doSomething(index: Int) {
self.array = [1, 2, 3]
}

var body: some View {
ForEach(0..<array.count) { i in
Text("\(self.array[i])")
.onTapGesture { self.doSomething(index: i) }
}
}
}

Using Array's Indices

The indices property is a range of numbers.

struct ContentView: View {
@State private var array = [1, 1, 2]

func doSomething(index: Int) {
self.array = [1, 2, 3]
}

var body: some View {
ForEach(array.indices) { i in
Text("\(self.array[i])")
.onTapGesture { self.doSomething(index: i) }
}
}
}

foreach loop get index of an object?

$i = 0;
foreach ($product as $key => $att) {
echo "index is: $i<br>";
$i++;
}

How to get array index from foreach loop

foreach ($_SESSION["products"] as $index => $cart_itm)

{
echo '<tr>';
echo '<td>' . $index . '</td>';
echo '<td>'.$cart_itm["code"].'</td>';
echo '<td>'.$cart_itm["name"].'</td>';
echo '<td>'.$cart_itm["qty"].'</td>';
echo '<td><input type="text" name="product_qty_desired" class="spinner" value="1" size="3" /></td>';
echo '<td>'.$currency.$cart_itm["price"].'</td>';
echo '<td class="subtotal">Subtotal : </td>';
echo '<td><span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'">×</a></span></td>';
echo '</tr>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
}

With the arrow operator, you can select the index in a foreach loop.

How can I get the current array index in a foreach loop?

In your sample code, it would just be $key.

If you want to know, for example, if this is the first, second, or ith iteration of the loop, this is your only option:

$i = -1;
foreach($arr as $val) {
$i++;
//$i is now the index. if $i == 0, then this is the first element.
...
}

Of course, this doesn't mean that $val == $arr[$i] because the array could be an associative array.

How do I get the index of an item inside of a ForEach loop?

You may go this way with an enumerated array:

   struct TempView: View{

@State var quarters: [[Month]] = [[.init(name: "January", products: ["1", "2"]),.init(name: "February", products: ["1", "2"]),.init(name: "March", products: ["1", "2"])],
[.init(name: "April", products: ["1", "2"]), .init(name: "May", products: ["1", "2"]), .init(name: "June", products: ["1", "2"])]]

var body: some View {

ForEach (self.quarters.indices , id: \.self) { (index) in

VStack {
Spacer()
HStack {
Text("Q\(index)")
.font(.system(size: 40, weight: .black, design: .rounded))
Button("TestButton",action: {
self.quarters.append([.init(name: "January", products: ["1", "2"]),.init(name: "February", products: ["1", "2"]),.init(name: "March", products: ["1", "2"])])
})
}
Spacer()
}
}

}}


Related Topics



Leave a reply



Submit