Loops in PHP.
Tags: php, php7, loops, foreach
Published: 2019-02-09 11:28:00

---
title: Loops in PHP.
published: true
description: top wasting your time and execute the same block of code several times. Learn PHP loop types
tags: PHP, PHP7, Loops,foreach.
cover_image: https://thepracticaldev.s3.amazonaws.com/i/n8yu3i505yyeafwju6mc.jpg
---

Whether you live in Europe, in the United States or in any other part of the world, I am sure that you have had the opportunity to see a race at least once in your life.

 

As an Italian,

 

I spent hours and hours of my weekend watching an young Valentino Rossi skid with his Yamaha first and then Ducati, and Micheal Schumacher overtakes by a lap all the other Formula 1 drivers aboard his red Ferrari.

 

Now,

 

with a programmer's mind, those memories are translated into one of the basic features of all programming languages.

 

**Today you will learn all about loops.**

 

One of the phrases my computer science teacher used to say to me often was that:

 

_"Programmers are lazy people, who do not like doing the same things and especially do not like to waste time rewriting the same commands times and times again"_.

 

I want you to close your eyes for a second and imagine, for the duration of this article, to be a pilot.

 

![](http://anastasionico.uk/img/1/Lawn_mower_racing_finland.jpg)

 

Formula 1, MotoGP World Championship, NASCAR, even lawn mower racing do not matter.

 

(Yes it exists, check this out! Https://en.wikipedia.org/wiki/Lawn\_mower\_racing)

 

As mentioned,

 

today you will learn all about loops in programming languages.

 

**The purpose of loops is to execute the same commands several times.**

 

A bit like a driver who accelerates, brakes and steers during a race, same commands over and over again.

 

There are different types of loops, even if all of them have more or less the same functionality, each of them differs in features and modes of use.

 

The skill of a programmer is to figure out which one to use in which case.

 

In PHP there are 4 types of loops,

 

**while, do...while, for and**  **foreach****.**

 

Fortunately, given their name, they are easy to understand for a native English speaker.

 

the commands while and do...while repeating the loop until a condition is true.

 

As you will see shortly, given the high similarity between them, in this article I will explain while and do...while together.

 

The for command has the characteristic of repeating the code for a predetermined number of occasions.

 

So far, so good.

 

The foreach loop instead repeats the loop until the repeating elements do not end.

 

At the moment everything can seem confusing I know, just bear with me, the aha moment will come soon.

 ## About the series
 

This&nbsp;blog post that belongs to the series " **PHP basics for Expert developer**".

 

If you haven't already read the other articles

 

have a look at them&nbsp;  
 [PHP basics for expert web developers (1' part)](http://anastasionico.uk/blog/php-basics-for-web-developer)  
 [Construct and Comments of PHP 7](http://anastasionico.uk/blog/php-construct-comments)  
 [How to use variables (PHP 7)](http://anastasionico.uk/blog/php-variables)  
 [Composite variable in PHP (Arrays, Object and more)](http://anastasionico.uk/blog/composite-variable-in-php)  
 [PHP operators (part 1)](http://anastasionico.uk/blog/php-operators)  
 [PHP Operators (part 2)](http://anastasionico.uk/blog/php-assignment-reference-comparison)  
 [Conditional Structures in PHP](http://anastasionico.uk/blog/php-if-switch)  
 [Loops in PHP(Tutorial)](http://anastasionico.uk/blog/php-tutorial-for-while-foreach)

 
## do...while and while commands
**do..while**
 

_It's Sunday morning,_

 

_to be precise it is 11:53 am, the lights that indicate the start of the race goes off precisely at 12:00, not a second later._

 

_You put the helmet just polished by one of the mechanics and enter the cockpit while another mechanic shows you the last torque-power diagram obtained from the car early this morning,_

 

_It is the result of the last changes made to the engine after the qualifying test the day before._

 

_You leave the garage and still with your legs trembling, among thousands of fans sitting on the bleachers, you position the vehicle according to the position obtained during qualifying._

 

_Last one._

 

_Detached from a good 1 second from the second to last, a guy that is racing with a broken hand._

 

_On the other hand, this is your first race among the professionals, and the only task that the sporting director has given you is to warm up the tires and finish the test lap._

 

_Just one lap!_

 

![](http://anastasionico.uk/img/1/Sauber_at_the_start_grid_at_the_2003_Hungarian_Grand_Prix_(2).jpg)

 

_Then maybe, you will keep going with the rest of the race._

 

All programming languages allow creating loops,

 

**The purpose of these commands is to repeat the same block of code several times,**

 

In this section, you will see the do ... while loop and the while loop,

 

[They depend on a condition,](http://anastasionico.uk/blog/php-operators)  
 &nbsp;

 

If the condition is true the loop continues otherwise the loop stops and the code continues with the following command.

 

As a young and promising pilot your task now is to do at least one lap, then if you survive the stress, you can continue with the rest of the race.

 
```php
$stressLevel = 0; 
// the first lap is mandatory 
do { 
    echo "Doing a lap, stress = $stressLevel %. \n"; 
    $stressLevel += 20; 
} while ($stressLevel <= 100);
```
 

As previously said,

 

the do...while loop operates based on a condition.

 

It is a loop that requires code to make at least one cycle, if at the end of the lap the preset condition is verified, only then, the loop starts again, otherwise, the code block ends and the script continues with the following command.

 

In the example,

 

you just saw the condition depends on the level of stress accumulated during the lap,

 

at the beginning of the loop, the stress level is equal to 0.

 

at every turn, when the situation warms up, the stress level increases by 20,

 

Then the coding checks whether the $stress variable is less than or equal to 100 and continues.

 

In the above example, exactly 6 laps will be executed and the following strings will be printed:

 
```php
Doing a lap, stress = 0 %. 
Doing a lap, stress = 20 %. 
Doing a lap, stress = 40 %. 
Doing a lap, stress = 60 %. 
Doing a lap, stress = 80 %. 
Doing a lap, stress = 100 %.
```
 

Since this series of articles is called "PHP basics for expert web developer" you will now see something a bit more complicated.

 

Do not worry if you do not understand the code right away, just go ahead and come back here when you feel ready.

 
```php
$redFlag =  false; $errstring = ""; 
do {    
    if (!isset($pilotOne)) {        
        $redFlag = true;        
        $errstring = "$pilotOne missing";        
        break;    
    }    
    if (isValidInput($pilotOne) == false) {        
        $redFlag = true;        
        $errstring = 'Invalid value for $pilotOne';        
        break;    
    }    
    $value1 = $pilotOne;        
    if (!isset($pilotTwo)) {        
        $redFlag = true;        
        $errstring = "$pilotTwo missing";        
        break;    
    }    
    if (isValidInput($pilotTwo) == false) {        
        $redFlag = true;        
        $errstring = 'Invalid value for $pilotTwo';        
        break;    
    }    
    $value2 = $pilotTwo; 
} while (0); 
if ($redFlag == true) {    //display the $errstring here. }
```
 

while(0) is a powerful hack used by C programmers for years,

 

**Practically being 0 equal to false, we pre-establish that this loop is going to do only one lap.**

 

Why do we do this?

 

This code-snippet is self-explanatory.

 

Having already read the previous articles of this series you should be able to understand what the code does.

 

Look at how this same code can be much more complicated if I was choosing to use&nbsp;only a series of if statements.

 
```php
$redFlag = false;
$errstring = "";
 
if (isset($pilotOne)) {
    if (isValidInput($pilotOne) == true) {
        $value1 = $pilotOne;
    } else {
        $redFlag = true;
        $errstring = "invalid value for pilotOne";
    }
} else {
    $redFlag = true;
    $errstring = "pilotOne is missing";
}
if (($redFlag == false) && isset($pilotTwo)) {
    if (isValidInput($pilotTwo) == true) {
        $value2 = $pilotTwo;
    } else {
        $redFlag = true;
        $errstring = "invalid value for pilotTwo";
    }
} else {
    if (! isset($pilotTwo)) {
        $redFlag = true;
        $errstring = "pilotTwo is missing";
    }
}
```
 

Not only is this code much more complicated to read and in the long run it creates a lot of mental clutter,

 

but this series of if ... else is not even able to verify all the possible conditions.

 

[A big shout to the tutorial of Pankaj Pal, programmer C and author of the article "useful do while(0) trick" I used in this example,](http://edusagar.com/articles/view/6/useful-do-while0-trick)

 
## while loop
 

After the first test lap, the fear and the stress level is greatly reduced and you start to get used driving the vehicle.

 

You decide to continue with the race.

 

Great!

 

Now there is another problem, the rules say that except in the case of brake problems (good luck with that) you can not make any pit-stops.

 

Via radio, the technicians reassure that everything will be fine and the vehicle has been assembled according to the best standards but, they also recommend one thing:

 

in the tank and behave accordingly.

 
```php
$tankLevel = 100;
while ($tankLevel > 0) {
    echo $tankLevel--;
}
```
 

The while loop is the simplest of all,

 

both for syntax and for reasoning.

 

It too derives from the programming language C and consists of:

 

**Given a condition (in your case the level of gas in the vehicle) the code block inside is executed if the condition is true otherwise the script executes the next command.**

 

the difference with the do...while seen above simply lies in the fact that here the **condition is checked immediately** (at the beginning of each lap) instead of **later**.

 
## for loop
 

_The 15th lap has just begun, you take a look at the gas gauge and you realize that, as the most experienced driver, you have been able to manage the level of fuel in the vehicle in an exceptional way._

 

_There are only 5 laps left at the end of the race and you have not yet used half the tank while three-quarters of the rivals have already left the race._

 

_The gas is no longer a problem and now there are great incitements coming from the mechanics via radio._

 

_you MUST finish the race._

 

![](http://anastasionico.uk/img/1/Motogp_rossi_300.jpg)

 

Let's move now from the easiest among the loops to the syntactically more difficult one.

 

**The for loop is also derived from C and evaluates different expressions, divided by semicolons, on single or multiple variables.**

 

If the expressions verified within the brackets are true, the code within the block is executed.

 

Here is an example:

 
```php
for ($lap = 15; $lap <= 20; $lap++) {
    echo "lap n. $lap.";
}
```
 

The first expression indicates the current state of the situation, the value of the variable at the time we approach the loop for the first time,

 

As told in our story we are on the 15th lap.

 

In the second expression, we indicate the condition we want to verify for the code block to be executed, our race ends at the 20th lap.

 

Eventually,

 

like all loops, we have to increase the variable, in this case, one lap at a time. nothing new here.

 

Note that increase the variables on which we are basing the loop is mandatory.  
 If avoided, the loop will continue forever, and forever is a very long time.

 

It is worth mentioning that if you are brave enough, the loop for is very user-friendly and provides different types of syntax to experiment with.

 

For example,

 

even if the "spaces" for the three expressions are mandatory and with them, the semicolons that act as dividers, the expressions themselves can be excluded.  
 &nbsp;

 
```php
for ($lap = 15; ; $lap++) {
    if ($lap > 20) {
        echo "Race completed.";
        break;
    }
        echo "lap n. $lap.";
}
```
 

The two examples above work exactly the same way,

 

Both cycles through a variable, both increase the value of the variable by 1 each time and both end when the value of the variable reaches 20.

 

As you can see from the block just above in this case we have replaced the second expression of the loop with an if command inside the block and finished the iteration with the command break.

 

**It is not mandatory to insert the expressions inside the parentheses.**

 

Here is another snippet even more advanced:

 
```php
$lap = 15;
for (; ; ) {
    if ($lap > 20) {
        echo "Race completed.";
        break;
    }
    echo "lap n. $lap.";
    $lap++;
}
```
 

The same is true in this last example, the important thing is to set the initial value of the variable, to indicate a condition to end the loop and increase the variable each loop.

 

**Where you decide to perform these three tasks is up to you.**

 

...

 

Have you ever heard of "colon syntax"?

 

I still remember the day I discovered this PHP feature.

 

It was a cold night of typical English winter a few years ago and I was studying a tutorial created by [Jeffrey Way](https://twitter.com/jeffrey_way?lang=en), creator of the [Laracasts](https://laracasts.com/)site.

 

Give it a look, lot's of value there.

 

PHP supports this special syntax on for loops:  
 &nbsp;

 
```php
for ($lap = 15; $lap <= 20; $lap ++) :
    echo "lap n. $lap.";
endfor;
```
 

**It seems very similar to the original (and it is) but I can guarantee that if used in the middle of HTML tags or in a view (in an MVC model) it will really make a difference,**

 

Both in terms of clarity and in terms of mental clutter.

 

Last but not least,

 

I left the case where the loop evaluates more than one variable at a time.

 

It is a very rare case and it is quite an advanced use of the for loop,&nbsp;

 

The example below has been stolen shamelessly from the PHP.net website.

 
```php
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
```
 

**Homework: Take a look at the examples and write in the comment below or in the linked facebook page what you think the result would be.**

 
## foreach loop
 

_The last lap of the race, meanwhile another couple of vehicles left the race and by now we are at the moments that count._

 

_The heart beats fast, now you know the track like your pockets, so do your opponents._

 

_Turn right, reduce gear, accelerate and prepare to pull off corners_

 

_The gap between you and the others is just a matter of milliseconds, the overtaking one another continue for the duration of the ride._

 

_You are momentarily in the second position, your foot is deep on the accelerator pedal, you take the windbreak from the first for the whole duration of the last straight before the final corner, late-braking and overtaking from the inside of the corner,_

 

_First, the first position and only 200 meters to go,_

 

_..._

 

_Beep! beep! beep! beep!_

 

_The darkness suddenly._

 

_This sound, almost annoying, does not come from any of the dashboard lights,_

 

_There's no dashboard, just dark._

 

_It is time to remove the sleep eye mask, get out of bed and turn off the alarm._

 

_Let’s go, It is already morning and you have some code to write._

 
### Array and object in foreach&nbsp;loops
 

The last type of loop of the article.

 

**The**  **foreach**  **construct allows looping through elements that include the Traversable interface.**

 

**In simple words,**

 

**it works on arrays and objects.**

 

If you want to learn more about them here is what the official manual says about [Arrays](http://php.net/manual/en/language.types.array.php)and [Object](http://php.net/manual/en/language.types.object.php).

 

There are only two syntaxes, which however are very similar to each other.

 

The simplest assigns the value of the current element to a variable.

 
```php
$racers = ["Marc Marquez", "Andrea Dovizioso", "Valentino Rossi", "Maverick Vinales"];
foreach ($racers as $racer) {
    echo "$racer \n" ;
}
```
 

The foreach loop above simply takes an array of names, in this case, the name of MotoGP riders ordered by the position of last year's championship and echo them out.

 
### Associative arrays in foreach&nbsp;loops
 

In case of associative arrays or objects is frequent the use of foreach that includes both the key and the value of the element.

 
```php
$drivers = [
    “Mercedes” => "Lewis Hamilton", 
    “Ferrari” => "Sebastian Vettel", 
    “Ferrari” => "Kimi Raikkonen", 
    “Red Bull Racing” => "Max Verstappen"
];
foreach ($drivers as $constructor => $driver) {
    echo "$driver drives a $constructor. \n" ;
}
```
 

**In this case, the array is formed by a key-value pair divided by an arrow =\>,**

 

![](http://anastasionico.uk/img/1/2627816570_de32f68714.jpg)

 

we can iterate both using the second syntax made available by PHP.

 

it allows us to insert the key of our array (it may be an object) into the _$constructor_ variable and the value in the _$driver_ variable.

 

But, how does a foreach work internally?

 

Its behaviour has changed with the passing of the years, however from the version 5 of PHP onwards it functions stayed very much the same.

 

**When a**  **foreach**  **loop starts an internal pointer is instantiated.**

 

**It always points to the element after the current one,**

 

**each time a loop is completed, the internal pointer automatically returns to the first element of the array**

 

There are several commands in PHP that modify the behaviour of the pointer but this practice is reserved for programmers with a certain level of experience as modifying a pointer inside a loop can involve unexpected behaviours.

 

Here is the list of functions that work on array pointers:

 

**reset()**&nbsp;Set the internal pointer of an array to its first element  
 **current()**&nbsp;Return the current element in an array  
 **each()** Return the current key and value from an array  
 **end()**&nbsp;Set the internal pointer of an array to its last element  
 **next()**&nbsp;Advance the internal pointer of an array  
 **prev()**&nbsp;Rewind the internal array pointer  
 **array\_key\_first()**&nbsp;Gets the first key of an array  
 &nbsp;

 
### Passing variables by reference
 

You have seen that there are several methods to read an array or an object using the foreach loop.

 

But, what about changing the elements inside the array?

 

As a default mode, PHP loops over the elements in a modality called "by value", that is, it only accesses the index of the variable present in the memory, without touching the value itself.

 

**To actually modify array elements, the value must be assigned "by reference".**

 

To do this, just enter the & symbol before the desired value.

 
```php
$racers = ["Marc Marquez", "Andrea Dovizioso", "Valentino Rossi", "Maverick Vinales"];
foreach ($racers as &$racer) {
    $racer = strtoupper($racer);    
}
unset($racer);
// $racers now is equal to: "MARC MARQUEZ", "ANDREA DOVIZIOSO", "VALENTINO ROSSI", "MAVERICK VINALES"

```
 

Note that when looping through by reference, the last element of the library remains in memory.

 

To avoid unpleasant problems it is good practice to eliminate the variable using the PHP _unset()_ function on the variable as shown above.  
 &nbsp;

 
### list() function inside foreach loop
 

Another fun trick that you can use with arrays and foreach that makes it easier to read the code is to use the _list()_ function.

 

In a way is like _list__()_ assign variables pretending they were an array.

 

In the snippet below the variable _$racers_ contains the first element of the nested array while _$drivers_ the second and they are shown in order.

 
```php
$pilots = [
    ["Marc Marquez", "Andrea Dovizioso", "Valentino Rossi", "Maverick Vinales"],
    ["Lewis Hamilton", "Sebastian Vettel", "Kimi Raikkonen", "Max Verstappen"],
];
 
 
echo "2018 standings: \n"
foreach ($pilots as list($racer, $driver)) {
    echo "MotoGP: $racer; Formula 1: $driver\n";
}
 
// the result shown will be:
2018 standings:
MotoGP: Marc Marquez; Formula 1: Lewis Hamilton
MotoGP: Andrea Dovizioso; Formula 1: Sebastian Vettel
MotoGP: Valentino Rossi; Formula 1: Kimi Raikkonen
MotoGP: Maverick Vinales; Formula 1: Max Verstappen
```
 
## Conclusion
 

Loops are not scary at all,

 

Obviously like everything else, it takes a bit of practice.

 

**Being able to figure out when to use one type of loop instead of another, remembering the exact syntax and using loops on multidimensional arrays or even objects inside other objects is not easy.**

 

But this is still part of the basics of PHP and other languages.

 

Testing, experimenting and improving day after day is the key to creating a solid foundation that will be used to create increasingly complex web applications.

 

_Maybe you will not become a professional driver or win championships as a racer but I hope that after reading this tutorial you have improved, at least a little, as a web developer._

 

...

 

If you want more or haven't read the other parts yet, Do not miss out!  
 [PHP basics for expert web developers (1' part)](http://anastasionico.uk/blog/php-basics-for-web-developer)  
 [Construct and Comments of PHP 7](http://anastasionico.uk/blog/php-construct-comments)  
 [How to use variables (PHP 7)](http://anastasionico.uk/blog/php-variables)  
 [Composite variable in PHP (Arrays, Object and more)](http://anastasionico.uk/blog/composite-variable-in-php)  
 [PHP operators (part 1)](http://anastasionico.uk/blog/php-operators)  
 [PHP Operators (part 2)](http://anastasionico.uk/blog/php-assignment-reference-comparison)  
 [Conditional Structures in PHP](http://anastasionico.uk/blog/php-if-switch) [Loops in PHP(Tutorial)](http://anastasionico.uk/blog/php-tutorial-for-while-foreach)

 

...
[![subscribe-Medium.jpg](https://cdn.filestackcontent.com/8FTfVAyCSAOjiU4yLcIM)](http://eepurl.com/dIZqjf)
 

Also Learning new skills is never a simple process but fortunately, unlike years ago, it has been made much easier in the present day.

 

Living practically on the web, one of the applications that helped me a lot in my career is the eLearning platform teamtreehouse .

 

[They are currently making a free 4-month offer (valued at $ 100).](http://treehouse.7eer.net/c/1374240/294479/3944)

 

[Have a look at it!.](http://treehouse.7eer.net/c/1374240/294479/3944)

 

([Affiliate links](http://treehouse.7eer.net/c/1374240/294479/3944))