How to Find the foreach Index with PHP

In this tutorial, we provide you with helpful methods to find the foreach index in PHP.

Below, you can find three options with proper examples.

Applying the key Variable

The key variable contains the index of every value inside the foreach loop. In PHP, the foreach loop is used like this:

foreach($arrayName as $value){
    //code
}

The value variable contains the value of every element of the array. Here is an example:

<?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";
}   
?>

Here, the key variable stores the index of the foreach loop. The variable value demonstrates the value of every element within the array.

The output will look as follows:

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

Applying the index Variable

The index variable is applied as an additional variable for demonstrating the index of the foreach loop in any iteration.

Here is an example:

<?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";
}
?>

It is essential to consider that the index variable should initially be initialized with a value. Afterwards, it increments any time the loop iterates.

The output will look like this:

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

Applying the key and index Variables

Now, let’s see how using both the key and index variables will look like.

Here is an example:

<?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";
}
  
?>

In the example above, the value of the key variable is kept with an increment within the index variable. So, in this case, both the key and index variables are used for finding the index of foreach.

Describing the foreach Loop in PHP

In PHP, the foreach loop is applied for looping through a block of code for every element inside the array. It is essential to note that the foreach loop only operates on objects and arrays. Once you try to use it on a variable with a different data type, it will issue an error.

Do you find this helpful?

Related articles