PHP loops sig­ni­fic­antly reduce de­vel­op­ment time by auto­mat­ing re­pet­it­ive tasks. The flex­ib­il­ity of loops lets you customise the number of passes or respond to specific con­di­tions.

What is a PHP loop?

PHP loops are extremely useful for auto­mat­ing re­pet­it­ive tasks, pro­cessing data or searching through lists and PHP arrays. You can execute a specific statement or code block re­peatedly without needing to write it over and again. Use in PHP functions or PHP classes is also possible. This enhances the ef­fi­ciency of PHP ap­plic­a­tions. It also con­trib­utes to overall code main­tain­ab­il­ity by providing a struc­tured way to organise and manage re­pet­it­ive tasks.

Tip

Deploy Now from IONOS provides strong in­fra­struc­ture and stability, and offers a wide range of powerful auto­ma­tion functions to deploy your projects quickly and easily.

What types of PHP loops are there?

There are different types of PHP loops, including:

  • For loops: This loop is used to execute an in­struc­tion a certain number of times. It consists of an ini­tial­isa­tion ex­pres­sion, a condition, and an increment.
  • While loops: The while loop executes an in­struc­tion as long as a specified condition is true.
  • Do-while loops: Similar to the while loop, but the condition is checked after the statement has been executed. This guar­an­tees that the code is called at least once.
  • Foreach loops: PHP foreach can iterate over elements in an array or list and apply the commands to each element.
Tip

To learn more about the basics of the PHP pro­gram­ming language, check out the PHP tutorial from our guide. We’ve also created an overview of the ad­vant­ages and dis­ad­vant­ages of PHP vs Python and PHP vs JavaS­cript for you.

The syntax of PHP loops

The syntax of PHP loops varies depending on the loop type, but they all follow a similar basic pattern with a condition and a code block.

PHP loop: for loop

The for loop is suitable when you already know in advance how many times you want to repeat a block of code. Its syntax typically looks like this:

for (init counter; test counter; increment counter) {
    code to be iterated;
}
php
  • init counter: This initial value marks the starting point for the loop and is where you typically ini­tial­ise a variable.
  • test counter: This condition is evaluated every time the loop runs. As long as this condition remains true, the loop body is executed. When the condition turns false, the loop stops executing.
  • increment counter: This step specifies how the initial value is in­cre­men­ted or decre­men­ted with each pass of the loop. It’s often referred to as the ‘increment’ operation.

PHP loop: while loop

You should use a while loop if you’re not sure how often the code block needs to be repeated.

while (condition is true) {
    code to be executed;
}
php
  • condition: This is an ex­pres­sion condition that gets evaluated before each iteration of the loop.

Do-while loop in PHP

Re­gard­less of the condition, the code is executed at least once for do-while.

do {
    code to be executed;
} while (condition is true);
php
  • condition: This is the ex­pres­sion condition that is evaluated after the initial execution of the code block.

Foreach loop in PHP

This loop is par­tic­u­larly useful to go through the elements of a list or an as­so­ci­at­ive array (an array with key-value pairs).

foreach ($array as $value) {
    code to be executed;
}
php
  • $array: the array to be traversed or the iterable data type
  • value: a temporary variable that rep­res­ents the value of an element in the array in each loop pass
IONOS Developer API
Manage your hosting products through our powerful API
  • DNS man­age­ment
  • Easy SSL admin
  • API doc­u­ment­a­tion

Examples of the use of the various PHP loops

When selecting a suitable PHP loop, consider its prop­er­ties and con­di­tions.

For loop

Here’s an example of a for loop in PHP that outputs the numbers from 1 to 5:

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

First, we ini­tial­ise a variable $i with 1 as the start value. The loop continues as long as $i is less than or equal to 5 (the condition $i <= 5). Within the loop, we output the value of $i followed by a space. After each iteration, we increase the value of $i by 1 by using $i++. As output we get ‘1 2 3 4 5’.

Do while loop

The code block in a PHP do while loop is executed before the condition is checked.

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

If you call this code, it will output ‘1 2 3 4 5’, just like the previous for loop.

While loop

The while loop is suitable if you use PHP to retrieve in­form­a­tion from a MySQL database among other reasons.

$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 create an SQL query to retrieve all user data from the user table. We execute the SQL query with mysqli_query and check if the query was suc­cess­ful. Then we use a while loop to iterate through the results of the query and display the user data.

PHP foreach

Here’s an example of the foreach loop in PHP to iterate through an array and display the elements:

$fruits = ["Apple", "Banana", "Cherry", "Date", "Fig"];
foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}
php

We use the echo function to display each fruit from the ‘fruits’ array, and we add a line break (<br>) for a clearer layout.

IONOS Cloud Object Storage
Cloud storage at an un­beat­able price

Cost-effective, scalable storage that in­teg­rates into your ap­plic­a­tion scenarios. Protect your data with highly secure servers and in­di­vidu­al access control.

Go to Main Menu