How to use PHP loops to repeat program sequences automatically
PHP loops significantly reduce development time by automating repetitive tasks. The flexibility of loops lets you customise the number of passes or respond to specific conditions.
What is a PHP loop?
PHP loops are extremely useful for automating repetitive tasks, processing data or searching through lists and PHP arrays. You can execute a specific statement or code block repeatedly without needing to write it over and again. Use in PHP functions or PHP classes is also possible. This enhances the efficiency of PHP applications. It also contributes to overall code maintainability by providing a structured way to organise and manage repetitive tasks.
Deploy Now from IONOS provides strong infrastructure and stability, and offers a wide range of powerful automation 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 instruction a certain number of times. It consists of an initialisation expression, a condition, and an increment.
- While loops: The while loop executes an instruction 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 guarantees 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.
To learn more about the basics of the PHP programming language, check out the PHP tutorial from our guide. We’ve also created an overview of the advantages and disadvantages of PHP vs Python and PHP vs JavaScript 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 initialise 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 incremented or decremented 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 expression condition that gets evaluated before each iteration of the loop.
Do-while loop in PHP
Regardless 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 expression condition that is evaluated after the initial execution of the code block.
Foreach loop in PHP
This loop is particularly useful to go through the elements of a list or an associative 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 represents the value of an element in the array in each loop pass
- DNS management
- Easy SSL admin
- API documentation
Examples of the use of the various PHP loops
When selecting a suitable PHP loop, consider its properties and conditions.
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 . " ";
}
phpFirst, we initialise 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);
phpIf 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 information 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>";
}
phpHere 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 successful. 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>";
}
phpWe use the echo
function to display each fruit from the ‘fruits’ array, and we add a line break (<br>
) for a clearer layout.
Cost-effective, scalable storage that integrates into your application scenarios. Protect your data with highly secure servers and individual access control.