Multiple index variables in PHP foreach loop

In PHP, you can iterate through multiple arrays simultaneously using a foreach loop with index variables. This technique allows you to process corresponding elements from different arrays in a single loop.

Basic Syntax

When using foreach with multiple arrays, you access the index of one array and use it to retrieve elements from other arrays ?

<?php
$FirstArray = array('aB', 'PQ', 'cd', 'pm');
$SecondArray = array('12', '34', '90', '49');

foreach($FirstArray as $index => $value) {
    echo $FirstArray[$index] . $SecondArray[$index];
    echo "<br/>";
}
?>
aB12
PQ34
cd90
pm49

Multiple Arrays Example

You can extend this approach to work with more than two arrays ?

<?php
$names = array('John', 'Alice', 'Bob');
$ages = array(25, 30, 35);
$cities = array('New York', 'London', 'Paris');

foreach($names as $index => $name) {
    echo "Name: " . $names[$index] . ", Age: " . $ages[$index] . ", City: " . $cities[$index];
    echo "<br/>";
}
?>
Name: John, Age: 25, City: New York
Name: Alice, Age: 30, City: London
Name: Bob, Age: 35, City: Paris

Key Points

  • All arrays should have the same length to avoid undefined index errors
  • The loop iterates based on the first array's length
  • Use the index variable to access corresponding elements in other arrays
  • This method is more efficient than nested loops for parallel array processing

Conclusion

Using foreach with multiple index variables provides an efficient way to process corresponding elements from multiple arrays simultaneously. This technique is particularly useful when working with related data stored in separate arrays.

Updated on: 2026-03-15T08:48:20+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements