PHP Loops: Different Types of Loops in PHP With Flowcharts

Welcome to our PHP Loops discussion, where we discuss the different types of loops available in PHP along with some helpful flowcharts.

If you are curious about the for loop in PHP, the for loop in PHP, or how to effectively use for loops in PHP, you have come to the right place!

Let’s dive into the world of PHP loops together.

What are loops statements in PHP?

PHP Loops are control structures that allow a block of code to be executed multiple times or repeatedly as long as a certain condition is met.

PHP for loop function is useful for iterating over a block of code for a specific number of times.

If you already know the number of iterations needed, it is better to use a for loop. Otherwise, it would help if you used a while loop.

for loop centralizes all loop-related statements and helps users manage their code more efficiently.

What are the different types of loops in PHP?

Various Types of Loops in PHP:

  • while loop: It executes a block of code as long as the specified condition is true.
  • do-while loop: Similar to the while loop, it always executes the block of code at least once before checking the condition.
  • for loop: If you know how often you want to execute a statement or block of statements, use the for loop statement.
  • foreach loop: It is used to loop through arrays or collections.
  • break statement: It terminates the current loop and resumes execution at the next statement after the loop.
  • continue statement: It skips the rest of the current iteration and continues with the next iteration of the loop.

1. while loop

While a test expression remains true, the while statement executes a block of code.

This block of code is executed if the test expression yields a true value. After executing the code block, the test expression is reassessed, and the loop persists until the test expression evaluates to false.

According to PHP Documentation, the purpose of a while statement is straightforward.

It instructs PHP to repeatedly execute the nested statement(s) as long as the while expression evaluates to true.

Syntax:

while (condition) {
    // code to be executed
}

In this example, we use a while loop to print numbers from 1 to 5.

<?php
// Initialize a variable
$count = 1;

// While loop to print numbers from 1 to 5
while ($count <= 5) {
    echo "Number: " . $count . "<br>";
    $count++; // Incrementing the variable
}
?>

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

  • We start by initializing a variable $count to 1.
  • Then, we use a while loop with the condition $count <= 5, which means the loop will continue executing as long as $count is less than or equal to 5.
  • Inside the loop, we echo the current value of $count, followed by a line break <br>.
  • After printing the number, we increment the value of $count by 1 using $count++.
  • The loop continues until $count becomes greater than 5, at which point the condition becomes false, and the loop terminates.

2. do-while loop

The do…while statement executes a block of code at least once, and the loop continues as long as the condition remains true.

Syntax:

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

In this example, Printing Numbers with a do…while Loop in PHP.

<?php
// Initialize a variable
$counter = 1;

// Start a do...while loop
do {
    echo "Count is: " . $counter . "<br>";
    $counter++; // Increment the counter
} while ($counter <= 5); // Loop continues as long as counter is less than or equal to 5
?>

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
  • We start by initializing a variable $counter to 1.
  • The do…while loop is initiated with the do keyword, indicating that the code block within the curly braces {} will be executed at least once.
  • Inside the loop, we echo the current value of $counter, followed by a line break <br>.
  • After printing the value, we increment the $counter variable by 1 using $counter++.
  • The loop continues to execute as long as the condition $counter <= 5 remains true. This condition ensures that the loop stops when the counter reaches 6.
  • Since the loop executes at least once, even if the condition is initially false, it runs the code block before checking the condition.

3. for loop

When you already have a set number of times in mind for running a statement or a group of statements, that’s when you use the for statement.

A for loop is utilized when the user is aware in advance of the number of iterations required for executing the block of code. In other words, the predetermined number of repetitions is already established.

These loops can also be referred to as “entry-controlled loops.” The code comprises three key parts: the initialization, the test condition, and the increment.

Syntax:

for (initialization; condition; increment/decrement) {
    // code to be executed
}

In for loops, there’s a thing called a loop variable that controls how the loop operates. You start by assigning a value to this variable, then you check whether that value is less than or greater than the counter’s value.

If the statement turns out to be true, the loop body is executed, and the variable inside the loop is modified. This process repeats over and over until the exit condition is satisfied.

Initialization Expression: This is where we set the initial value for the loop counter. For instance, $num = 1;

Test Expression: Here, we check a condition. If it’s true, we run the loop’s body and then move to the update expression.
If it’s false, we exit the for loop. For example: $num <= 10;

Update Expression: After executing the loop body, this expression adjusts the loop variable by adding or subtracting some value. For example: $num += 2;

<?php
// Adding a string before printing numbers from 1 to 5 using a for loop
echo "The printing numbers are: <br>";
for ($i = 1; $i <= 5; $i++) {
    echo $i . "<br>";
}
?>

Output:

The printing numbers are: 
1
2
3
4
5

foreach loop

Arrays can be traversed using the foreach statement.

During each iteration, the value of the current array element is assigned to the variable $value, and the array pointer is advanced to the next element.

Subsequently, the next iteration will process the subsequent array element.

Syntax:

foreach ($array as $value) {
    // code to be executed for each element in $array
}


Here’s an example demonstrating how to list the items in an array:

<?php
// Define an array
$arr_fruits = array("apple", "banana", "orange", "grape");

// Loop through the array and list the items
foreach ($arr_fruits as $fruit) {
    echo $fruit . "<br>";
}
?>

This code will output:

apple
banana
orange
grape

What is a Break Statement?

In PHP, a break statement is used within loops, such as for, while, or foreach loops, to exit the loop’s execution prematurely.

When the break statement is encountered inside a loop, it immediately stops the loop from further iterations and transfers control to the statement following the loop.

Using the PHP break keyword allows you to halt a loop before it completes its iterations.

Once the loop concludes, the subsequent statement outside the loop will be executed.

Syntax:

while (condition) {
    if (condition) {
        break;
    }
    // code to be executed
}

Example code:

<?php
// Loop through numbers from 1 to 10
for ($i = 1; $i <= 10; $i++) {
    echo $i . "<br>";

    // Break the loop when $i is equal to 5
    if ($i == 5) {
        echo "Loop is terminated at $i";
        break;
    }
}
?>

This code will output:

1
2
3
4
5
Loop is terminated at 5

  • We echo the current value of the loop variable $i followed by a line break <br>.
  • We check if the value of $i is equal to 5 using an if statement.
  • If $i equals 5, we echo a message indicating that the loop is terminated at that point.
  • We use the break statement to exit the loop immediately when $i is equal to 5.

What is a Continue Statement?

The PHP continue keyword interrupts the current iteration of a loop, but it doesn’t terminate the loop entirely.

Similar to the break statement, the continue statement is placed within the block of statements executed by the loop.

It’s typically accompanied by a conditional test.

When a loop encounters a continue statement, the remaining code within the loop for that iteration is skipped, and the next iteration begins immediately.

Syntax:

while (condition) {
    if (condition) {
        continue;
    }
    // code to be executed
}

Here is an example demonstrating the use of the break statement in PHP:

<?php
// Initialize a variable
$count = 1;

// Start a while loop
while ($count <= 5) {
    // Check condition inside the loop
    if ($count == 3) {
        // Skip iteration if condition is met
        $count++;
        continue;
    }

    // Code to be executed
    echo "Count is: " . $count . "<br>";

    // Increment the counter
    $count++;
}
?>

Output:

Count is: 1
Count is: 2
Count is: 4
Count is: 5

  • The loop iterates from 1 to 5.
  • When $count equals 3, the continue statement is executed, skipping the code inside the loop for that iteration.
  • As a result, the number 3 is skipped in the output, and the loop continues with the remaining iterations.

Conclusion

In this article, we’ve covered various types of loops in PHP and even offered flowcharts to make them easier to grasp.

We delved into the significance of break and continue statements, which serve as control mechanisms within PHP loops.

Lastly, if you’re keen on diving deeper into the topic of PHP loop types, feel free to drop a comment below. We’re eager to hear from you!

Leave a Comment