Find the index in foreach loop in PHP
This article demonstrates how to find the index in the foreach
loop in PHP.
1. Using Associative Arrays
An associative array associates values with keys, and consists of any number of comma-separated key => value
pairs. You can access the key-value pairs present in an associative array using the following foreach
syntax: It traverses the iterable pointed by $array
, and on each iteration, it assigns the current element’s key and value to $key
and $value
variables, respectively.
foreach ($array as $key => $value)
statement
However, this gives the current element of the associative array, and not the index of the current iteration of the foreach
loop. The idea is to maintain an explicit counter, starting with 0
, which gets incremented on each iteration of the loop.
1 2 3 4 5 6 7 8 9 |
<?php $array = array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'); $index = 0; foreach ($array as $key => $value) { echo "$key: $value present at index $index\n"; $index++; } ?> |
Output:
key1: value1 present at index 0
key2: value2 present at index 1
key3: value3 present at index 2
2. Numerically Indexed Array
Unlike associative arrays, the index is not explicitly specified in numerically indexed arrays. Since PHP does not distinguish between indexed and associative arrays, you can use the same foreach
loop syntax for numerically indexed arrays as well. Here, the key of the current element is the same as the current iteration index of the foreach
loop.
1 2 3 4 5 6 7 |
<?php $array = array('Orange', 'Mango', 'Banana'); foreach ($array as $key=>$value) { echo "$value present at index $key\n"; } ?> |
Output:
Orange present at index 0
Mango present at index 1
Banana present at index 2
That’s all about finding the index in the foreach
loop in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)