Loops in PHP are used to repeat a block of code multiple times. They are helpful when you need to perform the same task, like displaying numbers or processing items in an array.
Types of Loops in PHP
1. while Loop
The while
loop runs as long as the condition is true.
Syntax:
while (condition) { // Code to run }
Exmple:
<?php $count = 1; while ($count <= 5) { echo $count . " "; $count++; } // Output: 1 2 3 4 5 ?>
2. do-while Loop
Similar to while
, but it always runs at least once, even if the condition is false.
Syntax:
do { // Code to run } while (condition);
Example:
<?php $count = 1; do { echo $count . " "; $count++; } while ($count <= 5); // Output: 1 2 3 4 5 ?>
3. for Loop
The for
loop is used when you know in advance how many times you want to repeat the code.
Syntax:
for (initialization; condition; increment) { // Code to run }
Example:
<?php for ($i = 1; $i <= 5; $i++) { echo $i . " "; } // Output: 1 2 3 4 5 ?>
4. foreach Loop
The foreach
loop is specifically used to iterate through arrays.
Syntax:
foreach ($array as $value) { // Code to run }
Example:
<?php $colors = array("Red", "Green", "Blue"); foreach ($colors as $color) { echo $color . " "; } // Output: Red Green Blue ?>
Key Points
- while: Use when the number of repetitions depends on a condition.
- do-while: Similar to while but runs at least once.
- for: Best when you know how many times to loop.
- foreach: Perfect for arrays or lists.