Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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? } 
like image 868
lovespring Avatar asked Sep 20 '09 02:09

lovespring


People also ask

How do you get the index of an element in a forEach loop?

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.

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

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.

Can we get index in forEach JS?

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.

How do you find the index of the current element in an 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.


2 Answers

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.

like image 124
Kip Avatar answered Oct 07 '22 01:10

Kip


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.

like image 26
Fabien Snauwaert Avatar answered Oct 07 '22 00:10

Fabien Snauwaert