Page Content

Tutorials

PHP Loops: Achieving Repetitive Tasks Through Iteration

PHP Loops

PHP control structures regulate the program’s execution flow. Loop control structures and conditional control structures are among them. Loop control structures are used to repeat specific operations or run code a predetermined number of times based on predetermined criteria. We call this process iteration. There are various loop types available in PHP, and in general, one loop type can be changed into another.

While, do…while, and for are the three primary loop types that PHP offers for managing iteration. Iterating across arrays and objects is made possible via the foreach loop, another loop structure.

while Loops

Many people believe that the while loop is the most basic kind of loop. Its fundamental components are a statement or block of statements to be performed and a truth expression (or condition). At the start of every iteration, the condition is assessed. The loop continues after the statement or statements inside it are executed if the expression evaluates to true. The statement or statements inside the loop are skipped and the loop terminates if it evaluates to false. If the initial condition is false, the while loop code block will not run.

While loops are useful for reading lines from a file to the end or getting rows from a database query when the number of iterations is unknown.

To incorporate many statements in a while loop, use curly brackets {}. Another form for the while loop that PHP allows is endwhile; at the end of the loop block and a colon : after the condition.

Example while loop:

<?php
$num = 1; // Initialize counter
while ($num <= 5) { // Condition checked at the start 
  echo $num . "<br />"; // Statement(s) to repeat
  $num++; // Modify the counter
}
// This code prints numbers from 1 to 5
?>

If the condition never evaluates to false, a while loop may have the potential to create an infinite loop.

do while Loops

Although the do while Loops and the while loop are similar, the do while loop differs significantly in that it evaluates the truth expression at the conclusion of each iteration. Even if the condition is initially false, this guarantees that the statement or block of code inside a do while loop is always run at least once.

The basic structure is do statement while (expression);

If a certain condition is met, do while loops can occasionally be used as a graceful method to exit a code block. The break statement is used inside the loop body to escape when necessary in certain situations, and the while condition may be set to false.

Example do...while loop:
<?php
$num = 100; // Variable initialised so condition is false 
do {
  echo $num . "<br />"; // Code block executes at least once 
  $num++; // Modify the variable
} while ($num < 1); // Condition checked at the end 
// This code prints 100 once because the condition ($num < 1) is false initially
?>

Although helpful in certain situations, the do…while loop is not as frequently used in real-world applications as the while loop.

for Loops

PHP for loops are written in the C-style. They give loops that usually need a counter or known number of iterations an organised method to be handled. Initialisation, condition, and increment/step are all combined into one line using the structure: for (start_expressions; truth_expressions; increment_expressions) statement;.

  • Only once, at the very start of the loop, is the start expression evaluated. Usually, the loop control variable is initialised using this method.
  • Every iteration begins with an evaluation of the truth expression (condition). The code inside the loop runs if it is true; if it is false, the loop ends.
  • Before the truth expression is tested again, the increment expression is assessed at the conclusion of each iteration, following the execution of the loop body. It is frequently used to change the loop control variable, like when a counter is increased.

For loops work especially well when the number of iterations is fixed. Similar to other control structures, for loops support the alternate colon syntax with endfor; and can include a single statement or a block of statements enclosed in curly braces. A for loop requires the semicolons to be present, but all three expressions are optional. The functionality of a while loop can theoretically be implemented by a for loop.

Example for loop:

<?php
//     initialization ; condition ; increment 
for ($i = 0;         $i < 5;    $i++) { // Three parts in one place 
  echo "This is loop number " . $i . "<br />\n"; // Code executed per iteration
}
// This example prints a message for loop numbers 0 through 4
?>

PHP‘s foreach loop is another loop structure made especially for iterating over array and object elements. Foreach is frequently more convenient because it is configured especially for this purpose and can provide you access to both keys and values, even though you can use for loops to iterate across arrays. An array can be completely iterated over using foreach, even if its keys are unknown. An object must implement the Iterator interface to iterate over it using foreach.

Example foreach loop iterating over values:

<?php
$colours = ['red', 'green', 'blue'];
foreach ($colours as $colour) { // Iterating over array values 
  echo $colour . "<br />\n";
}
// This prints each colour in the array
?>

Use foreach ($array as $key => $value) to get the key and value. With endforeach;, foreach also supports the alternative colon syntax.

Breaking Out of Loops (break, continue)

The break and continue statements are provided by PHP to provide you additional control over the flow inside loops.

  • Break. Execution of the current for, foreach, while, do…while, or switch structure is instantly stopped by the break statement. When a break occurs, the statement that comes right after the ended structure is where execution goes.
  • The syntax is as simple as break;. The switch statement or innermost loop is terminated in this fashion. Additionally, break can take an extra numeric parameter, break n;, that indicates the number of nested enclosing structures from which to break. Break 1; is the same as break;. When break n; is used, a switch statement is considered to be at the loop level.
  • When a particular event or fault condition within a loop renders it impossible or unnecessary to continue the iteration, a break is helpful. For switch statements to be useful, it is necessary.
  • An illustration of a break in a loop:
  • In a while(true) endless loop, where you depart based on an internal condition, break is also frequently used.
  • Proceed For looping structures (for, foreach, while, do…while), the continue statement is used to skip the remainder of the current iteration and move on to the start of the subsequent one. It doesn’t completely break the loop like break does.
  • This is the basic syntax: continue;. By doing this, the innermost loop’s current iteration is skipped, and the subsequent iteration is started. Additionally, continue can take an optional integer parameter, continue n;, which specifies the number of nested loop levels to skip until the end of.
  • In a for loop, the increment expression is assessed right after the continue without waiting for the truth expression to be re-evaluated. It is important to make sure that the variable that controls the loop condition is changed before the continue statement is reached in while and do…while loops [as suggested by loop mechanics].
  • An illustration of a continuing loop:
  • The loop can skip a problematic value (0) while still processing the remaining values in the sequence, as shown in this example.

Loop structures are essential PHP control structures that let you repeat code blocks effectively. The loop’s entrance and exit conditions can be defined in a variety of ways using the while, do…while, and for loops, while the loop body can be used to fine-tune the execution flow with break and continue.

Index