PHP Loops: For, While, Do-While & Foreach Guide
In PHP, there are several common ways to loop:
- For loop: Used to repeatedly execute a code block a specified number of times.
for ($i = 0; $i < 10; $i++) {
echo $i;
}
- While loop: the code block is repeated as long as the given condition is true.
$i = 0;
while ($i < 10) {
echo $i;
$i++;
}
- Do-while loop: execute a code block, then check the condition, and repeat the code block as long as the condition is true.
$i = 0;
do {
echo $i;
$i++;
} while ($i < 10);
- foreach loop: used to iterate through each element in an array.
$fruits = array("apple", "banana", "orange");
foreach ($fruits as $fruit) {
echo $fruit;
}
- A foreach loop can iterate through the keys and values of an associative array.
$person = array("name" => "John", "age" => 30);
foreach ($person as $key => $value) {
echo $key . ": " . $value;
}
These are commonly used looping methods in PHP, and you can choose the appropriate one based on your specific needs to achieve the desired functionality.