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.

Download  Run Code

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.

Download  Run Code

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.