FOR PHP Loop Guide with Examples

The FOR loop in PHP is another iterative structure just like the loop while. Its operation is identical but the way of programming it varies. For this reason, I recommend that if you have not read the publication on the WHILE loop (it is very complete), I recommend that you read it: how the while loop works and how the while loop is used.

He flowchart of a for , that is, as executed by the code interpreter (usually Apache), it would be as follows:

Content

  • Structure of a For php loop
    • The initialization of the for loop
    • Updating a loop
  • For Loop Example
    • Stepping order of execution of a for loop
  • Approach to using For loops php
  • Abstract For Loop Concepts
    • Other PHP concepts

Structure of a For php loop

The structure of the FOR statement in PHP is the following: its name (for), the data initialization that we want, one or more conditions in parentheses, an update of information that will be executed when a repetition ends, and some braces to indicate on which lines it acts.

It would look like this:

<?php
for ( $contador = 0; $contador < 10; $contador = $contador + 1 ) {
}
?>

You’ve understood? Inside the parentheses are the three zones that I have mentioned (data initialization; condition; update).

Knowing its structure is the first step to start use the loops for in a normal way in our developments.

The initialization of the for loop

Initialization refers to the creation or preparation, depending on interest, of a variable or element that marks when the loop will begin to perform iterations.

If for example we are asked to count from 1 to 10, my initialization could be $var = 1.

Because?

Well, because my strategy will be to perform 10 repetitions (hereinafter iterations) with a loop and to achieve this I will need a counter, that is, a variable that I can keep checking in the condition of the loop until cease to be fulfilled (it is what we must think when making loops), or what is the same, it is evaluated as false, in programming the value boolean FALSE.

That being said, what better way to solve the problem than to make my counter coincide with the start of the value to be displayed on the screen.

The following practical example solves the problem:

<?php
for ( $var = 1; $var <= 10; $var = $var + 1 ){
    echo $var;
}
?>
Devolverá:
1
2
3
....
10

That $var = 1 is the initialization.

You may be wondering: is it possible to create the loop without initialization? As a general rule we will say that it is impossible, although it can be done (things of the senior developer).

How am I going to tell the loop a condition if I haven’t initialized a variable so I can compare?

There are a thousand and one possible implementations of FOR in programming., the structure will always be the same, but there will be changes in the way of using it, for example not all of them will use it with a counter.

When you start programming, the vast majority of your first FOR loops will be through a counter that you will have to initialize.

Updating a loop

The update it is directly related to the initialization of the loop.

In the previous example, I have initialized the variable $var to 1 and I have indicated to the loop through the condition $var <= 10 that, as long as the value of $var is less than or equal to 10, it executes the lines of code between its braces.

But what will make those repetitions possible will be the update (the third part inside the parentheses), which changes the value of the counter for each repetition.

The update is executed every time the loop has been iterated, that is, all the code between its braces has been executed..

In this area (update) of the FOR loop I can perform the operations that I need to be executed at the end of each iteration.

Programming in this area of ​​the FOR is similar to writing this same code on the last line before the closing brace.

The example above the update is the third part of the loop $var = $var + 1:

<?php
for ( $var = 1; $var <= 10; $var = $var + 1 ){
    echo $var;
}
?>

As I have told you, in this example, writing the FOR PHP update in its corresponding place is similar to doing it in the last line:

<?php
for ( $var = 1; $var <= 10; ){
    echo $var;
   $var = $var + 1;
}
?>

Updating a loop for PHP refers to the lines of code where the value of one or more variables on which the execution or not of the loop lines depends is modified.

In this way, the condition of the loop will evaluate to false at some point and its execution will be terminated.

Otherwise, if the loop does not end, we will have a Infinite loop.

For Loop Example

Let’s see a more complex example with which to work the PHP statement FOR:

php exercise: Create a script that calculates the factorial of a number, for the example use 5.

Solution:

<?php 
//ejemplo de factorial de numero 5
$factorial = 1;
for($numero = 5; $numero > 1; $numero = $numero - 1 ) {
   $factorial = $factorial * $numero;
}
echo ' El factorial de ' . $numero . ' es ' . $factorial.
?>

This little script computes the factorial of 5 and, upon completion, displays the result with a threw outthat is, the loop performs the calculation of a factorial 5 * 4 * 3 * 2 * 1.

If we were to monitor the execution of the exercise code (which is called trace) we would see that the calculations that are made and in the order executed are: 5 * 1 * 4 * 3 * 2.

In the FOR loop, if we compare it with a WHILE, the three parts are much more differentiated.

The update involves the subtraction of 1 from the number: $number = $number – 1.

Stepping order of execution of a for loop

We are going to follow Apache’s execution of the loop, or as we programmers would say, we are going to trace the problem. For the trace, basically what we will do is read the problem as the machine would read it, that is, the php code interpreter. For example our companion Apache server.

The following description will be each of the instructions that are executed, line by line, with a description of the values ​​that can intervene between parentheses to make it clear. I recommend that you have your code handy to follow along as you read:

  1. $factorial = 1;
  2. $number = 5;
  3. $number > 1 ??? ( 5 > 1 ? true condition, we continue )
  4. $factorial = $factorial * $number ( $factorial = 5 * 1 )
  5. $number = $number – 1 ( $number = 5 – 1 );
  6. $number > 1 ??? ( 4 > 1 ? the condition is true, we keep repeating )
  7. $factorial = $factorial * $number ( $factorial = 5 * 4 )
  8. $number = $number – 1 ( $number = 4 – 1 )
  9. $number > 1 ??? ( 3 > 1 ? true )
  10. $factorial = $factorial * $number ( $factorial = 20 * 3 )
  11. $number = $number – 1 ( $number = 3 – 1 )
  12. $number > 1 ??? ( 2 > 1 ? true )
  13. $factorial = $factorial * $number ( $factorial = 60 * 2 )
  14. $number = $number – 1 ( $number = 2 – 1 )
  15. $number > 1 ??? ( 1 > 1 ? false condition, loop code is not executed )
  16. echo ‘ The factorial of ‘ . $number . ‘ is ‘ . $factorial ( The factorial of 5 is 120 )
  17. end

He Flowchart of this script would be:

Approach to using For loops php

He main approach of a loop for It is based on identifying the three parts seen: initialization, condition, update.

The first question we must ask ourselves when we detect that we need a for loop is how many iterations does my loop require?

Once we know the number of repetitionseither a concrete number or dependent on the value of a variable, we must begin to divide into parts the problem.

Let’s review the approach that I followed with the previous example (the one that calculates the factorial of a number):

  1. If we analyze the operation of calculating the factorial of a number, such as the number 4 (4*3*2*1 ) we see 4 numbers involved in the operation, but since I really multiply by two (4*3, 12*2, 24*1) we get 3 operations. So, for a factorial of 4 I will have 3 operations, and for a 5 it will be 4. Therefore, the number of iterations of my loop will be the number I want to calculate the factorial minus 1: $number – 1. Now that we know that the loop depends entirely on the variable $number.
  2. initialization It will then be the variable that marks the evolution of the loop: $number.
  3. Now comes the condition, a somewhat confusing part when one starts. The condition must achieve along with the update to for the loop to do $number – 1 iterations. We also know that number must be multiplied by all numbers between $number and 1. We therefore conclude that the condition of the loop should be: $number > 1. I say greater and not greater than or equal to make sure that the WHILE does $number – 1 repetitions, that is, when $number has the value 1 the condition will no longer be fulfilled, if instead we say “>=” the loop would $number iterations.
  4. Lastly, the update I will do it 1 by 1, that is, decreasing the number until it reaches 1. When the loop ends one iteration, I will subtract 1.

Abstract For Loop Concepts

In summary, the concepts that we have seen in the lesson would be:

  • The PHP for loop is an iterative control structure..
  • A for loop in PHP is defined by its statement, an update, a condition, and a data update. It also has a number of lines of code in braces that will be executed as long as the condition is met.
  • When the loop condition for is false the loop will finish executing. The code interpreter will follow the line just after the closing brace of the loop.

Updating a loop for PHP refers to the lines of code where the value of one or more variables on which the execution or not of the loop lines depends is modified. In this way, the condition of the loop will evaluate to false at some point and its execution will be terminated. Otherwise, if the loop does not end, we will have a Infinite loop.

Other PHP concepts

In addition to what has been seen, if you are learning PHP I recommend other of my articles on PHP:

  • Using variables in php
  • Arithmetic operations with php variables
  • control structures
  • How loops work in php

Leave a Reply