In this tutorial, we will show you how to find the current index key of a foreach loop in PHP.
Let’s loop through an array and print out the key of the current element:
//Example array
$fruits = array(
0 => 'Apple',
1 => 'Bananna',
2 => 'Pear'
);
//Loop through the array
foreach($fruits as $key => $value){
//Print the index
echo "The key/index of $value is: $key
";
}
If you run the PHP code above, it will print out the following:
As you can see, the key variable in the foreach loop will always contain the key of the current element.
This will also work with associative arrays:
$carDetails = array(
'make' => 'Honda',
'mode' => 'Civic',
'year' => '2023'
);
foreach($carDetails as $key => $value){
echo "$key: $value <br>";
}
The example above will result in the following:
As you can see, it doesn’t matter if the key is numeric or not.