About Lesson
PHP Loops
Loops are used to run a block of code several times until a specific condition is met.
1. for Loop:
The for loop is used when we know ahead of time how many times we want to run the code.
Syntax:
for(initialization; condition; increment/decrement) {
// code to be executed
}
- initialization: Set a starting value.
- condition: The loop will continue as long as this condition is true.
- increment/decrement: Increase or decrease the value after each iteration.
Example:
PHP
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i <br>";
}
?>
Explanation:
- It prints the number from 1 to 5.
2. while Loop
The while loop runs as long as the condition is true. It checks the condition before executing the code.
Syntax:
while(condition) {
// code to be executed
}
Example:
PHP
<?php
$i = 1;
while ($i <= 5) {
echo "Number: $i <br>";
$i++;
}
?>
3. do-while Loop:
The do-while loop is like the while loop, but the code runs at least once, even if the condition is false. This happens because the condition is checked after the code executes.
Syntax:
do {
// code to be executed
} while (condition);
Example:
PHP
<?php
$i = 1;
do {
echo "Number: $i <br>";
$i++;
} while ($i <= 5);
?>
4. foreach Loop:
The foreach loop is used only for arrays. It loops through each element of the array.
Syntax:
foreach($array as $value) {
// code to be executed
}
Example1: Simple Array
PHP
<?php
$colors = ["Red", "Green", "Blue", "Yellow"];
foreach ($colors as $color) {
echo "Color: $color <br>";
}
?>
Example1: Associative array
PHP
<?php
$student = [
"Name" => "John",
"Age" => 21,
"Course" => "PHP"
];
foreach ($student as $key => $value) {
echo "$key: $value <br>";
}
?>