DEV Community

Mateusz Jasiński
Mateusz Jasiński

Posted on

PHP 0 to hero pt.6 - Loops

Hi and hello. The sixth part of this tutorial is here - today, a very important topic. Loops

As always, that's how this article will be divided:

  1. Theory - What is a loop, why they are useful etc.
  2. For loop
  3. while and do-while loops
  4. foreach loop

And that's pretty much it - let's go

Theory of loops

Let's visualize something:

There is a big web-app with comments, that we are working on. We get assigned to the task, that requires us to write a function, that will change the accounts name to it's ID in every post they have made. There are a 100 thousand comments with one nickname.

Will we spend half of our life manually inputting, which comment should have a change - of course not

That's pretty much what loops are for - to perform the same tasks, desired number of times

So, going back to our example. In pseudo-code it would look something like this

Loop start{
    getIDFromNickname;
    changeNicknameToID;
}
Enter fullscreen mode Exit fullscreen mode

And this is it - now, we have 4 types of loops

For loop

That's actually the hardest one, yet still really popular.

It looks like this

for (expr1; expr2; expr3){
    // code inside
}
Enter fullscreen mode Exit fullscreen mode

What are these expressions?

expr1 - A short code, executed right at the beginning, no matter what.
In 90% of for loops, that's a declaration of loop counter - a special variable, that will be used later to check how many times code inside a loop was executed
We almost always declare it as $i

expr2 - This expression is evaluated right at the beginning of each iteration (In simpler words: An execution of a code inside a loop).

If expression returns true - code is executed
If false - loop ends

There, we use Comparison Operators - I talked about them in the previous article

And a third one - exp3
It's the expression executed at the end of an iteration.
We mostly use it to increment (add 1 to the variable - very fancy word)

To visualize, we may write a simple pseudo-code:

for(The beginning of the loop; before each iteration; after each iteration){
   // Code to execute
}
Enter fullscreen mode Exit fullscreen mode

So - let's print Hello Loops! 10 times with for loop

for($i = 0; $i < 10; $i++){
    echo "Hello Loops!<br/>";
}
Enter fullscreen mode Exit fullscreen mode

And if we want to "read" it:

set $i to 0
If $i < 10 execute code inside, else finish the loop
Increment $i and go back to the previous step

That's it - now the second one

while loop

While loop is a little easier, as it takes only one parameter - a expresion

According to the docs:

It (while loop) tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to true

So, if we write the loop like this:

$i = 1;
while($i <=10){
    echo "while is cool</br>";
    $i++;
}
Enter fullscreen mode Exit fullscreen mode

We tell the program to execute code inside it, if at the beginning of each iteration the condition in brackets is met

(And by the way, we use the iterator again)

Talking about the while loop, there is also another, similar loop

do-while

It works alike the while loop, but with one major difference

The expression is evaluated in the end of each iteration, not the beginning. That's why do-while is better when we need to execute the code inside it at least once, for example while removing a directory or asking user repeatably for similar input

Now, it looks like this:

$i = 1;
do{
    echo "do-while is cool too</br>";
    $i++;
}while($i <=10)
Enter fullscreen mode Exit fullscreen mode

So, the last one is left

foreach loop

Personally, I use it the most.

foreach is the easiest way to iterate through the arrays

So, If we have an array that looks like this:

$numbers = [1,2,3,4,5,6,7,8,9,10];
Enter fullscreen mode Exit fullscreen mode

And we want to create a new array with that numbers, but to the power of 2

Instead of for loop

$powers = [];

for($i = 0; $i < count($numbers); $i++){ 
    array_push($powers, $numbers[$i]**2);
}

// result: 1 4 9 16 25 36 49 64 81 100 
Enter fullscreen mode Exit fullscreen mode

(Quick explanation. count() is a function, that counts elements in the array)

We can write simpler - foreach

$powers = [];
foreach($numbers as $number){
    array_push($powers, $number**2);
}
// result: 1 4 9 16 25 36 49 64 81 100 
Enter fullscreen mode Exit fullscreen mode

Much more readable isn't it?

That's it, you have now learned how to write and use loops in PHP

Conclusion

I hope this article was useful and you understood everything I explained.

Loops are crucial concept in programming, so this article is important

Btw, I hope you have had a very nice Christmas and I wish you all a happy new year

See you in the next article

Top comments (0)