PHP Loop
In PHP, a loop is a control structure that allows you to execute a block of code repeatedly based on a specified condition or for a fixed number of iterations. Loops are essential for automating repetitive tasks and processing data efficiently.
PHP offers several types of loops:
- For loop
- While loop
- Do while loop
- Foreach loop
A for loop is used when you know in advance how many times you want to execute a block of code. It consists of an initialization statement, a condition, and an update statement.
Syntax
for (condition is true)
{
// Code to execute repeatedly
}
// Code to execute repeatedly
}
Example
While loop
A while loop is used to execute a block of code as long as a specified condition remains true.
Syntax
while (condition is true)
{
// Code to execute repeatedly
$counter++;
}
Example
Do while loop
A do-while loop is similar to a while loop, but it guarantees that the code block will execute at least once, even if the condition is initially false.
Syntax
do {
// Code to execute repeatedly
} while (condition is true);
Example
Foreach loop
A foreach loop is used to iterate over the elements of an array or the properties of an object.
Syntax
foreach ($array as $value); {
// Code to execute for each element
}
Example