php array iteration foreach loop key value array_walk

PHP Array Iteration

PHP array iteration can be done only by loops and iteration functions, for example, foreach loop with key and value and etc. The PHP foreach construct provides an easy way to iterate over arrays, especially multidimensional array. foreach works only on arrays and objects. Let’s talk about the PHP array iteration with an example for each section with the key and value.

PHP comes with three different types of arrays to help you store data. You can either use simply indexed (numerical) arrays or you can create associative arrays or multidimensional arrays.

Indexed arrays are helpful when you want to just store a list of items.

Associative arrays are useful when you want to store key-value pairs like a list of customer IDs and the total value of products purchased by each one.

Multidimensional arrays are useful to store arrays in an array. This array can save an Indexed or Associative array or both.

In this tutorial, we are going to discuss how to iterate a PHP array with value and key.

PHP Array Iteration with key and value

In this section, you are going to learn methods and techniques to iterate a PHP array.

Iterate PHP array by foreach loop with key and value and example

As we mentioned, it can be done by foreach. You can do the iteration PHP array by other loops too but the foreach loop is the easiest way. But don’t worry we will discuss all loops here.

Read More About PHP Loops

There are two syntaxes for foreach:

foreach (iterable_expression as $value)
    statement

foreach (iterable_expression as $key => $value)
    statement

The first form traverses the iterable given by iterable_expression. On each iteration, the value of the current element is assigned to $value. This method is suitable for Indexed arrays.

$cars = array('Ferrari', 'Benz', 'BMW', 'Volvo');

foreach($cars as $car){
  echo $car . "<br/>";
}

Output

Ferrari
Benz
BMW
Volvo

In this PHP array iteration example, we create an array of car names to iterate with foreach loop.

The second form will additionally assign the current element’s key to the $key variable on each iteration. This method is suitable for associative arrays. PHP array foreach iterates if the key exists, otherwise foreach will not execute.

$cars = array("fer" => "Ferrari","ben"=>"Benz","bmw"=>"BMW","vol"=>"Volvo");

foreach($cars as $key => $car){
  echo $key . " => " . $car . "<br/>";
}

Output

fer => Ferrari
ben => Benz
bmw => BMW
vol => Volvo

For loop to iterate an array

For loop is a little different from the foreach loop. This loop is more operates like the while and do while loop.

For Indexed arrays, you can use the for loop normally.

$cars = array('Ferrari', 'Benz', 'BMW', 'Volvo');

for($counter = 0; $counter < count($cars); $counter++){
    echo $cars[$counter] . '<br/>';
}

Output

Ferrari
Benz
BMW
Volvo

This way is suitable for arrays that are normal. But sometimes elements can be removed from the array or added a new one and indexes are not in order anymore. In this situation, you can use the following method.

$cars = array('Ferrari', 'Benz', 'BMW', 'Volvo');

$keys = array_keys($cars);
for($counter = 0; $counter < count($keys); $counter++){
    echo $cars[$keys[$counter]] . '<br/>';
}

Output

Ferrari
Benz
BMW
Volvo

If your array is an Associative array, you can use the above code too.

$cars = array("fer" => "Ferrari","ben"=>"Benz","bmw"=>"BMW","vol"=>"Volvo");

$keys = array_keys($cars);
for($counter = 0; $counter < count($keys); $counter++){
    echo $keys[$counter] . " => " . $cars[$keys[$counter]] . '<br/>';
}

Output

fer => Ferrari
ben => Benz
bmw => BMW
vol => Volvo

While loop

For Indexed arrays, you can use the while loop normally too.

$cars = array('Ferrari', 'Benz', 'BMW', 'Volvo');

$counter = 0;
while($counter < count($cars)){
    echo $cars[$counter] . '<br/>';
    $counter++;
}

Output

Ferrari
Benz
BMW
Volvo

This way is suitable for arrays that are normal. But the problem of the unordered indexes stands here too. In this situation, you can use the following method.

$cars = array('Ferrari', 'Benz', 'BMW', 'Volvo');

$keys = array_keys($cars);
$counter = 0;
while($counter < count($cars)){
    echo $cars[$keys[$counter]] . '<br/>';
    $counter++;
}

Output

Ferrari
Benz
BMW
Volvo

If your array is an Associative array, you can use the above code too.

$cars = array("fer" => "Ferrari","ben"=>"Benz","bmw"=>"BMW","vol"=>"Volvo");

$keys = array_keys($cars);
$counter = 0;
while($counter < count($cars)){
    echo $keys[$counter] . " => " . $cars[$keys[$counter]] . '<br/>';
    $counter++;
}

Output

fer => Ferrari
ben => Benz
bmw => BMW
vol => Volvo

do … while

With do…while loop you have to check if the array has an element or not.

$cars = array("fer" => "Ferrari","ben"=>"Benz","bmw"=>"BMW","vol"=>"Volvo");

$keys = array_keys($cars);
$counter = 0;
$count = count($cars);

if($count > 0){
    do{
        echo $keys[$counter] . " => " . $cars[$keys[$counter]] . '<br/>';
        $counter++;
    }while($counter < $count);
}

Output

fer => Ferrari
ben => Benz
bmw => BMW
vol => Volvo

This method needs a little extra code effort from the while loop.

As you can see, foreach is the easiest and the best loop method for PHP array iteration. Now let’s talk about other methods.

PHP array iteration array_walk() function

This function is similar to the array_map() function, but with a slight difference. In this function, the array is sent by reference to the function.

 array_walk(array|object &$array, callable $callback, mixed $arg = null): bool
  • array – It is the input array to iterate over.
  • callback – It is a function passed to this function that will act on each item one by one. This function takes two parameters – 1. Item value 2. Index position of the item
  • args – It is the optional argument that if supplied, will be passed as the third parameter to the callback function.

It returns true when executed successfully.

$cars = array(
    "fer" => "Ferrari",
    "ben" => "Benz",
    "bmw" => "BMW",
    "vol" => "Volvo"
);

array_walk($cars,function(&$car,$key){
    $car = "$key is a key of $car";
});

var_dump($cars);

Output

array (size=4)
  'fer' => string 'fer is a key of Ferrari' (length=23)
  'ben' => string 'ben is a key of Benz' (length=20)
  'bmw' => string 'bmw is a key of BMW' (length=19)
  'vol' => string 'vol is a key of Volvo' (length=21)

Array Iterator

This method uses ArrayObject class to iterate an array. This will be a little advanced from the other methods.

Create an ArrayIterator object using the ArrayObject function and use it to iterate over an array. It is based on the pointer mechanism just like C++.

$cars = array(
    "fer" => "Ferrari",
    "ben" => "Benz",
    "bmw" => "BMW",
    "vol" => "Volvo"
);

$array_object = new ArrayObject($cars);
$array_iterator = $array_object->getIterator();
while( $array_iterator->valid() )
{
    echo $array_iterator->key() . " => " . $array_iterator->current() . "<br/>";
    $array_iterator->next();
}

Output

fer => Ferrari
ben => Benz
bmw => BMW
vol => Volvo

Iterate multidimensional array in PHP

$cars = array(
    'k1' => array(
        "name" => "Ferrari",
        "year" => 2022
    ),
    'k2' => array(
        "name" => "Benz",
        "year" => 2020
    )
);

foreach($cars as $car_key => $car){
    echo $car_key . '=> ';
    foreach($car as $key=>$details){
        echo $key . " => " . $details . " | ";
    }
    echo "<br/>";
}

Output

k1=> name => Ferrari | year => 2022 |
k2=> name => Benz | year => 2020 | 

This example shows how to iterate a PHP multidimensional array with foreach loop.

$cars = array(
    'k1' => array(
        "name" => "Ferrari",
        "year" => 2022
    ),
    'k2' => array(
        "name" => "Benz",
        "year" => 2020
    )
);

$car_keys = array_keys($cars);
for($cc = 0; $cc < count($car_keys); $cc++){
    $detail_keys = array_keys($cars[$car_keys[$cc]]);
    echo $car_keys[$cc] . '=> ';
    for($dc = 0; $dc < count($detail_keys); $dc++){
        echo $detail_keys[$dc] . " => " . $cars[$car_keys[$cc]][$detail_keys[$dc]] . " | ";
    }
    echo "<br/>";
}

Output

k1=> name => Ferrari | year => 2022 |
k2=> name => Benz | year => 2020 | 

This example shows the iteration with for loop.

$cars = array(
    'k1' => array(
        "name" => "Ferrari",
        "year" => 2022
    ),
    'k2' => array(
        "name" => "Benz",
        "year" => 2020
    )
);

$car_keys = array_keys($cars);
$cc = 0;
while( $cc < count($car_keys)){
    $detail_keys = array_keys($cars[$car_keys[$cc]]);
    echo $car_keys[$cc] . '=> ';
    $dc = 0;
    while( $dc < count($detail_keys)){
        echo $detail_keys[$dc] . " => " . $cars[$car_keys[$cc]][$detail_keys[$dc]] . " | ";
        $dc++;
    }
    echo "<br/>";
    $cc++;
}

Output

k1=> name => Ferrari | year => 2022 |
k2=> name => Benz | year => 2020 | 

This works around the while loop.

$cars = array(
    'k1' => array(
        "name" => "Ferrari",
        "year" => 2022
    ),
    'k2' => array(
        "name" => "Benz",
        "year" => 2020
    )
);

$car_keys = array_keys($cars);
$cc = 0;
$ckc=count($car_keys);
if($ckc > 0){
    do{
        $detail_keys = array_keys($cars[$car_keys[$cc]]);
        echo $car_keys[$cc] . '=> ';
        $dc = 0;
        $dkc=count($detail_keys);
        do{
            echo $detail_keys[$dc] . " => " . $cars[$car_keys[$cc]][$detail_keys[$dc]] . " | ";
            $dc++;
        }while($dc < $dkc);
        echo "<br/>";
        $cc++;
    }while($cc<$ckc);
}

Output

k1=> name => Ferrari | year => 2022 |
k2=> name => Benz | year => 2020 | 

And the last loop is the do...while.

$cars = array(
    'k1' => array(
        "name" => "Ferrari",
        "year" => 2022
    ),
    'k2' => array(
        "name" => "Benz",
        "year" => 2020
    )
);

array_walk($cars,function(&$car,$car_key){
    echo $car_key . '=> ';
    array_walk($car,function(&$detail,$detail_key){
        echo $detail_key . " => " . $detail . " | ";
    });
    echo "<br/>";
});

Output

k1=> name => Ferrari | year => 2022 |
k2=> name => Benz | year => 2020 | 

In this way, we do an iteration of a multidimensional array in PHP.

$cars = array(
    'k1' => array(
        "name" => "Ferrari",
        "year" => 2022
    ),
    'k2' => array(
        "name" => "Benz",
        "year" => 2020
    )
);

$car_object = new ArrayObject($cars);
$car_iterator = $car_object->getIterator();
while( $car_iterator->valid() )
{
    echo $car_iterator->key() . '=> ';
    $detail_object = new ArrayObject($car_iterator->current());
    $detail_iterator = $detail_object->getIterator();
    while( $detail_iterator->valid() ){
        echo $detail_iterator->key() . " => " . $detail_iterator->current() . " | ";
        $detail_iterator->next();
    }
    $car_iterator->next();
    echo "<br/>";
}

Output

k1=> name => Ferrari | year => 2022 |
k2=> name => Benz | year => 2020 | 

And the last one, iterate by ArrayIterator.

These examples iterate a 2 dimension array, but what about 3 or for dimensions?

$cars = array(
    'k1' => array(
        "name" => "Ferrari",
        "year" => 2022
    ),
    'k2' => array(
        "name" => "Benz",
        "year" => 2020
    ),
    'k3' => array(
        "toy" => array(
            "name" => "Toyota",
            "year" => 2021
        )
    )
);

function iterate($array){
    foreach($array as $key => $value){
        if(is_array($value)){
            echo $key . '=> ';
            iterate($array[$key]);
            echo "<br/>";
        }
        else{
            echo $key . " => " . $value . " | ";
        }
    }
}

iterate($cars);

Output

k1=> name => Ferrari | year => 2022 |
k2=> name => Benz | year => 2020 |
k3=> toy=> name => Toyota | year => 2021 | 

In this example, we have a 3-dimensional array. This method uses the PHP recursive functions and foreach loop method to cover the multidimensional array.

What is the best way for PHP array iteration?

We introduced the iteration methods of the array in PHP in this article. Sometimes you have to choose one of these but if you want the best way, we recommend you the foreach loop method. Because this method is simple to understand and a fast way to code. Working with foreach loop with the key and value is more simple than the other methods

You may like

Shopping Cart