Home PHP What are the different types of loops available in PHP?

What are the different types of loops available in PHP?

Author

Date

Category

In PHP, there are several types of loops available to iterate over arrays, perform repetitive tasks, and control the flow of execution. Here are the main types of loops in PHP:

  1. for loop:
    The for loop is used when you know the number of iterations in advance.
for ($i = 0; $i < 5; $i++) {
    // Code to be executed
}
PHP
  1. while loop:
    The while loop is used when you want to repeat a block of code as long as a condition is true.
$i = 0;
while ($i < 5) {
    // Code to be executed
    $i++;
}
PHP
  1. do-while loop:
    The do-while loop is similar to the while loop, but it always executes the code block at least once, regardless of the condition.
$i = 0;
do {
    // Code to be executed
    $i++;
} while ($i < 5);
PHP
  1. foreach loop:
    The foreach loop is specifically designed for iterating over arrays or objects.
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
    // Code to be executed for each element
    echo $fruit;
}
PHP
  1. break and continue statements:
    The break statement is used to exit a loop prematurely, while the continue statement is used to skip the current iteration and move to the next one.
for ($i = 0; $i < 5; $i++) {
    if ($i == 2) {
        break; // Exit the loop when $i equals 2
    }
    if ($i == 1) {
        continue; // Skip the current iteration when $i equals 1
    }
    // Code to be executed
}
PHP


These are the most commonly used loop structures in PHP. They allow you to efficiently perform repetitive tasks and control the flow of execution based on certain conditions.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subhash Shipu

PHP Expert

Hey there! I'm a PHP geek on a mission to blog my way through the coding chaos. When I'm not chasing semicolons, I'm busy cuddling my pet Coco, who thinks debugging means chasing her own tail. Join the fun!

Subscribe

Recent posts