Codementor Events

Loops in PHP (Tutorial)

Published Feb 09, 2019Last updated Aug 07, 2019
Loops in PHP (Tutorial)

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.

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 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 
PHP basics for expert web developers (1' part)
Construct and Comments of PHP 7
How to use variables (PHP 7)
Composite variable in PHP (Arrays, Object and more)
PHP operators (part 1)
PHP Operators (part 2)
Conditional Structures in PHP
Loops in PHP(Tutorial)

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!

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,
 

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.

$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:

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.

$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 only a series of if statements.

$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,

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.

$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.

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:

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.
 

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:

$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, creator of the Laracastssite.

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

PHP supports this special syntax on for loops:
 

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, 

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

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 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 Arraysand Object.

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.

$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 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.

$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 =>,

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() Set the internal pointer of an array to its first element
current() Return the current element in an array
each() Return the current key and value from an array
end() Set the internal pointer of an array to its last element
next() Advance the internal pointer of an array
prev() Rewind the internal array pointer
array_key_first() Gets the first key of an array
 

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.

$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.
 

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.

$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)
Construct and Comments of PHP 7
How to use variables (PHP 7)
Composite variable in PHP (Arrays, Object and more)
PHP operators (part 1)
PHP Operators (part 2)
Conditional Structures in PHP Loops in PHP(Tutorial)

...
subscribe-Medium.jpg

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).

Have a look at it!.

(Affiliate links)

 ***

subscribe-Medium.jpg

Discover and read more posts from anastasionico
get started
post comments2Replies
Amelia_S
6 years ago

Hi,
great content thanks for sharing !

dafont 192.168.l.l filehippo

anastasionico
6 years ago

Hey Amelia, Thanks a lot