Synchronously iterate and print values from two arrays of the same size

Synchronously iterate and print values from two arrays of the same size

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why foreach Doesn't Accept Multiple Iterators and How to Fix It

The syntax you encountered in your code snippet is a common source of frustration for developers transitioning from PHP 4 or early PHP 5 examples. The logic behind attempting to iterate two arrays simultaneously using the and operator inside a single foreach loop stems from a misunderstanding of how PHP's control structures parse arguments.

In modern PHP, the foreach construct is designed strictly to iterate over one iterable (an array or Traversable object) at a time. While you can pass multiple variables to a function like list($code, $name) to capture values from an iteration, the loop itself must still be driven by a single source of truth—the iterator. The syntax $codes as $code and $names as $name is invalid because foreach does not evaluate boolean conditions with and to determine which arrays to traverse; it expects exactly one variable assignment for the key-value pair extraction.

To solve this, you need to decouple the iteration logic from the data access logic. The most robust approach in PHP 5.4 and later is to iterate over the primary array (usually the keys or the smaller dataset) and access the corresponding element in the secondary array using an index.

Here is a corrected implementation that maintains the exact behavior of your intended code:

$codes = ['tn', 'us', 'fr'];
$names = ['Tunisia', 'United States', 'France'];

// Iterate over $codes and access $names by index
foreach ($codes as $code) {
    $name = $names[$code]; // Assuming names are ordered or keyed by code
    
    echo '<option value="' . htmlspecialchars($code) . '">' . 
         htmlspecialchars($name) . '</option>';
}

However, there is a critical assumption hidden in the example above: the $names array must be indexed sequentially starting from 0 to match the length of $codes. If your arrays represent country codes and names where the code itself isn't the index (e.g., ['tn', 'us'] vs ['Tunisia', 'United States']), you are relying on parallel iteration by position.

If you need to iterate two arrays strictly by their indices without assuming one acts as a key, a simple for loop is often clearer and more performant than trying to force a foreach workaround:

$codes = ['tn', 'us', 'fr'];
$names = ['Tunisia', 'United States', 'France'];

$count = count($codes);
for ($i = 0; $i < $count; $i++) {
    echo '<option value="' . $codes[$i] . '">' . $names[$i] . '</option>';
}

This approach explicitly calculates the loop limit once, ensuring that both arrays are traversed exactly once. It fails safely if the arrays are not of the same size, preventing silent data loss or out-of-bounds errors that might occur if you blindly accessed $names[$code] in a keyed scenario.

Handling Different Array Sizes

A significant pitfall arises when the two arrays do not share the same length. If $codes contains 3 items but $names has only 2, direct parallel iteration will throw an Undefined array key error or access uninitialized values depending on your logic.

If you are building a form field using Laravel, you might consider binding data differently to ensure safety:

// Using collect for a more functional approach if needed
$codes = ['tn', 'us', 'fr'];
$names = ['Tunisia', 'United States', 'France'];

if (count($codes) === count($names)) {
    foreach ($codes as $index => $code) {
        echo '<option value="' . $code . '">' . $names[$index] . '</option>';
    }
} else {
    // Handle the mismatch scenario
}

Why This Matters for Select Boxes

When generating HTML <select> elements, the order and integrity of your data are paramount. A mismatched array can result in duplicate country names or empty options breaking the user interface. Using a single iterator (foreach) over the key array and accessing the value array by index is the standard pattern because it keeps the coupling explicit.

If you require a more dynamic solution where keys don't align with indices, consider merging the arrays into a single associative array first:

$data = array_combine($codes, $names);
// Result: ['tn' => 'Tunisia', 'us' => 'United States', ...]

foreach ($data as $code => $name) {
    echo '<option value="' . $code . '">' . $name . '</option>';
}

This transformation ensures that the output is generated based on the relationship between the two datasets rather than their positional order, offering greater resilience against data changes.

Our network