AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

PHP Loop: automatic repetition of program sequences

PARTAGEZ

PHP Loops reduce the development period considerably, as they allow repetitive tasks to be automated. There flexibility offered by these loops allows you to customize the number of repetitions or set a reaction based on certain conditions.

PHP Loops: what is it?

PHP loops are particularly useful for automate repetitive tasks, process data or browse lists or even PHP tables. This allows you to repeat the execution of a specific instruction or block of code, without having to write it multiple times. Likewise, don't hesitate to use PHP functions or PHP classes; This allows you to improve the efficiency of your PHP applications. This makes maintaining your entire program easier because you are able to organize repetitive actions within a clear structure.

Deploy Now is an IONOS solution that stands out for its robust infrastructure and high stability, but it also offers a wide range of powerful automation functions, to better enable you to deploy your projects quickly and easily.

What are the different types of PHP Loops?

There are different types of PHP loops, including:

  • THE for loops : they allow you to execute an instruction a certain number of times. They include an initial expression, a condition and an increment;
  • THE while loops : they execute an instruction, provided that the specified condition turns out to be “true”;
  • THE do while loops : they resemble while loops, but the condition is checked once the instruction is executed. So the code is called at least once;
  • THE foreach loops : in PHP, they allow you to iterate over the elements of an array or a list and apply commands to each element.

Do you want to learn more about the basic knowledge needed to use the PHP programming language? We advise you to consult the PHP tutorial, available in our Digital Guide. For you, we have also put together a quick comparison of the advantages and disadvantages of PHP and Python and PHP and JavaScript.

What is the syntax of PHP Loops?

The syntax of PHP loops depends on the type of loop used, but the basic schema always remains the same, with a condition and a block of code.

PHP Loop: for loop

The for loop may be suitable for you if you already know how many times the code should be repeated. Its syntax is as follows:

for (init counter; test counter; increment counter) {
  code to be iterated;
}

php

  • init counter : this is the starting value, the one with which the loop begins. A variable is normally initialized there;
  • test counter : this is the condition checked at each pass through the loop. As long as this condition remains true (” true “), the loop continues to execute. If the condition becomes false (“ false “), then the loop is interrupted;
  • increment counter : this is the part of the code allowing the initial value to be increased or reduced each time the loop is repeated. It can also be referred to as “increment”.

PHP Loop: while loop

Not sure how many times the code block should be repeated? We advise you to opt for a while loop.

while (condition is true) {
  code to be executed;
}

php

  • condition : this is an expression condition. This is evaluated before each new iteration of the loop.

Do while loop in PHP

The code is executed at least once with the do while loop, regardless of the condition.

do {
  code to be executed;
} while (condition is true);

php

  • condition : This is the expression condition checked after the first execution of the code block.

foreach loop in PHP

This loop can be particularly useful if you are looking to iterate through the elements of a list or a associative array (i.e. an array containing key-value pairs).

foreach ($array as $value) {
  code to be executed;
}

php

  • $array : this is the indication of the table to be browsed or the iterable data type;
  • value : this is a temporary variable which represents the value of an element of the array at each iteration of the loop.

Free IONOS API

Use the IONOS API at no additional cost to retrieve or update your domain, DNS and SSL data.

DNS records

SSL Administration

API Documentation

Application examples of different PHP Loops

When choosing the PHP loop that suits you best, remember to take its characteristics and conditions into account.

for loop

Below is an example of a for loop in PHP to display numbers from 1 to 5:

for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";
}

php

We start by initializing a variable “$i” with a starting value equal to 1. The loop repeats as long as “$i” remains less than or equal to 5 (the condition being “$i <= 5”). In the loop, we then print the value “$i”, followed by a space. After each iteration, we increase the value of “$i” by 1, this time using “$i++”. We therefore obtain the result “1 2 3 4 5”.

do while loop

The code block present in the do while loop is executed first and then the condition is checked.

$i = 1;
do {
    echo $i . " ";
    $i++;
} while ($i <= 5);

php

If you call this code, you will get the result “1 2 3 4 5”, exactly like in the previous for loop.

while loop

For example, it is appropriate to use the while loop when using PHP to retrieve information from a MySQL database.

$sql = "SELECT * FROM user";

$result = mysqli_query($conn, $sql);

if (!$result) {
    die("Query failed: " . mysqli_error($conn));
}

while ($row = mysqli_fetch_assoc($result)) {
    echo "username: " . $row["username"] . "<br>";
    echo "email: " . $row["email"] . "<br>";
    echo "age: " . $row["age"] . "<br>";
    echo "<hr>";
}

php

Here, we have created an SQL query in order to retrieve all the user data present in the table “ user “. We execute the SQL query with “mysqli_query”, and we ensure that it was successful. Finally, we use a while loop to iterate over the query results, and thus display the user data.

foreach loop in PHP

Below is an example of a foreach loop in PHP, which allows you to iterate through an array and display its elements:

$fruits = ["Apple", "Banana", "Cherry", "Date", "Fig"];

foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}

php

Here, we have chosen the “echo” function so as to display each fruit in the “fruits” table, with a newline (“
“) for a clearer presentation.

IONOS S3 Object Storage

IONOS S3 Object Storage is ideal for backups and archiving company data. You can store any amount of static data at low cost.

Scalable

Economic

Practical

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact

Suivez-nous:

© 2024 AMZ DIGICOM All Rights Reserved