PHP Tutorials

PHP Foreach Loop: Iterate Arrays with Examples

The PHP foreach loop lets you walk through arrays and change each element as you go. Here are clear examples plus the pitfalls to watch out for.

Serhat ALPASLAN3 min read

Contents

PHP

PHP FOREACH

php foreach lets us list the items inside an array within a loop. In other words, imagine a basket containing dozens of products; instead of writing each of those products out one by one, we do it with loops. One of the most widely used of the PHP loops is foreach.

Example:

$sepet = array('elma','armut','muz','nane','kivi','şeftali');

foreach($sepet as $urun){
        echo "$urun<br/>";
}

As you can see above, an array named sepet has been created, and the products are held inside that array. Instead of writing out the products in this sepet array one by one, we can easily do it with the help of a loop. Now let’s try the same example in a different way; this time our array will be a little different.

Example :

<?php 
$sepet = array(
    'urun1'=>'deneme',
    'urun2'=>'armut',
    'urun3'=>'muz',
    'urun4'=>'nane',
    'urun5'=>'kivi',
    'urun6'=>'şeftali'
    );
foreach($sepet as $uruntipi => $urunadi ){
        echo "Ürün Tipi :".$uruntipi." Ürün Adı :".$urunadi."<br/>";
}

In the syntax above, we printed the key and the value corresponding to that key. As you can see in the examples, with foreach we reached each element in the array in order. In the way foreach works, the loop runs as many times as there are elements in the array, and it starts from the first index, 0. On each iteration the index increases by 1 and continues. On each iteration the array’s values are assigned to a variable, and this is how we can reach each element. You can produce different examples by using loops together with conditions. We’ll also look at different usage styles related to these in the upcoming lessons.

Things to Watch Out For

Thing to Watch Out For Description
Naming the Loop Variable The variable name used in a foreach loop should specifically express the elements of the array.
Using References If you are going to make changes to the elements of the array in a foreach loop, the references of the elements should be used.
Initializing the Iterator First Before the foreach loop runs, it should be positioned at the beginning of the array. This is done by using the “reset()” function to position it at the start of the array.
Using More Than One Array Inside the Loop If more than one array is going to be used inside a foreach loop, a separate loop needs to be created for each array.
The Array Being Ordered The foreach loop processes the elements of the array in order. If order doesn’t matter, you can shuffle them randomly using the “shuffle()” function.

 

 

Share it if it helped

Write a comment