How do I get the current index in a foreach
loop?
foreach ($arr as $key => $val) { // How do I get the index? // How do I get the first element in an associative array? }
With the later C# versions so you also use tuples, so you'll have something like this: foreach (var (item, i) in Model. Select((v, i) => (v, i))) Allows you to access the item and index (i) directly inside the for-loop with tuple deconstruction.
C# Program to Get the index of the Current Iteration of a foreach Loop Using Select() Method. The method Select() is a LINQ method. LINQ is a part of C# that is used to access different databases and data sources. The Select() method selects the value and index of the iteration of a foreach loop.
In summary, the forEach() array iteration method accepts a callback function that holds arguments that can be used within the callback function for each array item, such as the array item, the index of the item, and the entire array.
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.
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.
This is the most exhaustive answer so far and gets rid of the need for a $i
variable floating around. It is a combo of Kip and Gnarf's answers.
$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' ); foreach( array_keys( $array ) as $index=>$key ) { // display the current index + key + value echo $index . ':' . $key . $array[$key]; // first index if ( $index == 0 ) { echo ' -- This is the first element in the associative array'; } // last index if ( $index == count( $array ) - 1 ) { echo ' -- This is the last element in the associative array'; } echo '<br>'; }
Hope it helps someone.
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