Loops in PHP


Loops in PHP

A loop is a language construct that allows you to execute a block of code more than once.

We are used to our scripts being executed in a linear fashion: from top to bottom, line by line, instruction by instruction. But what if you need to repeat some instruction several times?

For example, how to display natural numbers from 1 to 9? There is an obvious way:

<?php

print(1);

print(2);

print(3);

// and so on…

But, firstly, this method forces you to write a lot of code. Second, what if you want to output a sequence of a million numbers? And finally, there are situations when it is not known in advance how many times a certain instruction needs to be executed.

Using loops greatly simplifies and shortens the code. Also, loops are indispensable in situations where it is not known in advance how many times a block of code should be executed. Such a number can depend on many conditions and be calculated at the time the script is executed.

This is what a loop looks like in PHP:

<?php

while (<loop condition>) {

<loop body>

}

In the last chapter of the textbook, you got acquainted with the concept of an expression and its truth. Expressions are often used in loops in the following way: an expression is placed in place of <loop condition=””> and determines whether a block of code – <loop body=””> will be executed.

If the expression from the loop condition returns true, then execution will immediately go to the “loop body” block, but if it returns false, then the loop body will not be executed and the script will continue to run as usual, from the next line after the loop.

It turns out that cycles have such a name, because they seem to “loop” the usual, linear execution on their code block and prevent the script from executing further until the cycle condition is true.

It is important to understand the sequence in which code is executed when using loops.

The usual execution of code, line by line, until a cycle is encountered.

A cycle has been encountered: we fulfill the condition of the cycle.

If the condition returned false: exit the loop, execute the line after it and continue linear execution.

If the condition returned true: execute the entire body of the loop.

We repeat point 2.

Each sequence of steps 2-4, that is, the next execution of a block of code in the loop body, is called an iteration.

The number of iterations should be finite, that is, as a rule, the infinite execution of one block of code is not included in our plans.

This means that it is necessary to foresee the situation when the true condition becomes false.

Now let’s return to the task of displaying all natural numbers on the screen:

<?php

$last_num = 1;

while ($last_num < 10) {

    print($last_num);

    $last_num = $last_num + 1;

}

This loop contains two instructions in its body. The first displays the digit from the variable. The second instruction increments the value of the variable by one. Now the question is: how many times will such a loop be executed?

The loops are executed as long as their condition remains true, and in our condition the value of the variable must be less than ten. Since the initial value of the variable is one, it is not difficult to calculate that the loop will be executed exactly nine times. For the tenth time, the value of the $last_num variable will become equal to ten, and the condition $last_num < 10 will no longer be true.

Loops and arrays

Most often, loops are used to work with arrays. More specifically, to enumerate all the elements of the array and perform some action with each of these elements.

The ability to use loops and arrays together will immediately allow you to perform many interesting and varied tasks!

A little earlier, we already learned how to work with arrays. For example, we can show all the values ​​in an array by accessing each element by its index. But this is extremely tedious: accessing each of the elements of the array in turn, when we just want to show all its values. Cycles will get rid of this routine!

With loops, you can show the contents of any array and it only takes a few lines of code!

Let’s rewrite the example with the list of favorite TV shows, but now using a loop:

<?php

$fav_shows = [“game of thrones”, “american horror storry”, “walking dead”];

$cur_index = 0;

while ($cur_index < 3) {

    print($fav_shows[$cur_index] . “, “);

    $cur_index = $cur_index + 1;

}

In this example, the loop loops through the element by index. The index is now in the $cur_index variable and has an initial value of zero. The value of the variable increases by one with each iteration of the loop until it reaches three. At this point the condition $cur_index < 3 will no longer be true and the loop will stop after looping through the entire array.

Practice using array loops by completing this tutorial.

foreach – a special loop for arrays

It’s time to learn that loops in PHP can be of different types. Above, we got acquainted with the while loop. The main feature of this type is that it is necessary to specify an expression in its condition. But while is not the only kind of loop in PHP. There are at least two others.

Arrays and loops are used together so often that the language designers even added a kind of loop specifically for iterating over arrays. It’s called foreach. But what is wrong with the usual while and why did you need to come up with this foreach?

The point is that the while loop is too generic. And the price for this versatility will always be more complex and voluminous code. We have to come up with a condition, make sure that it is not infinite. And in the loop body, be sure not to forget to increment the counter variable. And all this is needed for a simple enumeration of the elements of the array. Can’t it be easier?

Fortunately, foreach solves all of these problems. Here are its capabilities:

no requirement to write a condition;

allows you to get the keys of an array;

itself assigns the next element of the array to a variable.

The foreach loop becomes absolutely indispensable when it comes to iterating over associative arrays. Let’s take this example: we have user data that is stored in an associative array. The site needed to make a page with information about this user. The task is to show on the page all the data that is known about this person. It should look like this:

Name: Eugene

Age: 27

Occupation: Programmer

The original array to be displayed like this:

$user = [

    ‘Name’ => ‘Eugene’,

    ‘Age’ => ’27’,

    ‘Occupation’ => ‘Programmer’

];

The script code that will iterate over the array and show all its contents will take only 4 lines:

foreach ($user as $key => $value) {

    print($key . ‘: ‘);

    print($value . ‘<br>’);

}

At each iteration of the loop, the variables $key and $value will be defined inside its body. The first one will contain the next array key, and the second one will contain the next value by this key.

Leave a Reply

Your email address will not be published. Required fields are marked *