For, while, do-while and for each.
In PHP, there are several types of loops that can be used to iterate over arrays, execute code blocks repeatedly, or perform looping based on certain conditions. The main types of loops in PHP include:
- for loop: A for loop is used when you know in advance how many times you want to execute a block of code.
php
for ($i = 0; $i < 5; $i++) {
// Code to be executed
}
- while loop: A while loop is used when you want to execute a block of code as long as a condition is true.
php
$i = 0;
while ($i < 5) {
// Code to be executed
$i++;
}
- do-while loop: Similar to a while loop, but the block of code is executed at least once, even if the condition is false.
php
$i = 0;
do {
// Code to be executed
$i++;
} while ($i < 5);
- foreach loop: Specifically used for iterating over arrays or collections.
php
$array = [1, 2, 3, 4, 5];
foreach ($array as $value) {
// Code to be executed for each element in the array
}
These loops provide flexibility in controlling the flow of your PHP scripts and are essential constructs in PHP programming. Understanding when to use each loop type and how to effectively utilize them can greatly improve the efficiency and readability of your code.