Find the Foreach Index in PHP
-
Use the
key
Variable to Find the Foreach Index in PHP -
Use
index
Variable to Find the Foreach Index in PHP -
Use Both
key
andindex
Variable to Find the Foreach Index in PHP

In this article, we will introduce methods to find the foreach
index.
- Using the
key
variable - Using the
index
variable - Using both the
key
andindex
variable
Use the key
Variable to Find the Foreach Index in PHP
The variable key stores the index of each value in foreach
loop. The foreach
loop in PHP is used as follows.
foreach($arrayName as $value){
//code
}
The variable value stores the value of each element of the array.
<?php
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($array as $key => $value) {
echo "The index is = " . $key . ", and value is = ". $value;
echo "\n";
}
?>
The key variable here contains the index of foreach
loop. The variable value shows the value of each element in the array.
Output:
The index is = 0, and the value is = 1
The index is = 1, and the value is = 2
The index is = 2, and the value is = 3
The index is = 3, and the value is = 4
The index is = 4, and the value is = 5
The index is = 5, and the value is = 6
The index is = 6, and the value is = 7
The index is = 7, and the value is = 8
The index is = 8, and the value is = 9
The index is = 9, and the value is = 10
Use index
Variable to Find the Foreach Index in PHP
The variable index is used as an additional variable to show the index of foreach
in each iteration.
<?php
// Declare an array
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$index = 0;
foreach($arr as $key=>$val) {
echo "The index is $index";
$index++;
echo "\n";
}
?>
Output:
The index is 0
The index is 1
The index is 2
The index is 3
The index is 4
The index is 5
The index is 6
The index is 7
The index is 8
The index is 9
Use Both key
and index
Variable to Find the Foreach Index in PHP
Now, we will use both the key variable and an additional variable index to find the index of foreach
.
<?php
// Declare an array
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$index = 0;
foreach ($arr as $key=>$value) {
echo "The index is $index";
$index = $key+1;
echo "\n";
}
?>
We have stored the value of the key variable with an increment in its value in the index variable. In this way, we can find the index of foreach
using both the key variable and index variable.
Output:
The index is 0
The index is 1
The index is 2
The index is 3
The index is 4
The index is 5
The index is 6
The index is 7
The index is 8
The index is 9