Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the foreach index?

Tags:

loops

foreach

php

Is it possible to find the foreach index?

in a for loop as follows:

for ($i = 0; $i < 10; ++$i) {    echo $i . ' '; } 

$i will give you the index.

Do I have to use the for loop or is there some way to get the index in the foreach loop?

like image 332
user18334 Avatar asked Sep 26 '08 18:09

user18334


People also ask

How do I get index PHP in foreach?

Use the key Variable to Find the Foreach Index in PHP The variable value stores the value of each element of the array. Copy <? php $array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); foreach ($array as $key => $value) { echo "The index is = " . $key .

How do I get current iteration in foreach?

by using automatic destructuring: foreach (var (value, i) in Model. Select((value, i) => ( value, i ))) { // Access `value` and `i` directly here. }

Does foreach have an index JavaScript?

Get The Current Array Index in JavaScript forEach() forEach(function callback(v) { console. log(v); }); The first parameter to the callback is the array value. The 2nd parameter is the array index.


1 Answers

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

$key is the index of each $array element

like image 96
Owen Avatar answered Sep 21 '22 18:09

Owen