Looping Statements in PHP
Looping statements in PHP are used to execute a block of code repeatedly until a specific condition is met. Loops help reduce redundancy and make the code more efficient.
PHP supports the following types of loops:
- for Loop – Executes a block of code a fixed number of times.
- while Loop – Executes a block of code as long as a condition is true.
- do-while Loop – Executes the code at least once, then repeats while a condition is true.
- foreach Loop – Iterates over arrays.
1. for Loop
A for loop in PHP is used to execute a block of code a specific number of times. It consists of three parts: initialization, condition, and increment/decrement. The loop runs until the condition evaluates to false. It is commonly used when the number of iterations is known.
Syntax:
for (initialization; condition; increment/decrement)
{
// Code to execute
}
Example:
<?php
for ($i = 1; $i <= 5; $i++)
{
echo "Number: $i <br>";
}
?>
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
2. while Loop
A while loop in PHP executes a block of code as long as the specified condition remains true. The condition is checked before each iteration, and if it evaluates to false, the loop stops. It is useful when the number of iterations is unknown beforehand.
Syntax:
while (condition)
{
// Code to execute
}
Example:
<?php
$x = 1;
while ($x <= 5)
{
echo "Value: $x <br>";
$x++;
}
?>
Output:
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
3. do-while Loop
A do-while loop in PHP executes a block of code at least once, regardless of the condition. After the first execution, it checks the condition, and if true, it repeats the loop. This is useful when you want the code to run at least once before validation.
Syntax:
do
{
// Code to execute
} while (condition);
Example:
<?php
$y = 1;
do
{
echo "Number: $y <br>";
$y++;
} while ($y <= 5);
?>
4. foreach Loop
A foreach loop in PHP is used to iterate over arrays, processing each element one by one. It simplifies looping through arrays without needing an index. The loop continues until all elements have been traversed, making it ideal for working with associative and indexed arrays.
Syntax:
foreach ($array as $value)
{
// Code to execute
}
Example:
<?php
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruitname)
{
echo "$fruitname <br>";
}
?>
Output:
Apple
Banana
Cherry
Looping statements in PHP make it easier to execute repetitive tasks efficiently. The for, while, do-while, and foreach loops are used based on different scenarios to control the program flow effectively.