Loops are used in PHP to repeat a block of code multiple times. There are four types of loops in PHP:
1. For Loop: The for loop is used to execute a block of code a fixed number of times. It has three parts: initialization, condition, and increment/decrement.
Syntax:
“`php
for (initialization; condition; increment/decrement) {
// code to be executed
}
“`
Example:
“`php
for ($i = 0; $i < 5; $i++) {
echo "The value of i is: " . $i . "
“;
}
“`
Output:
“`
The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
“`
2. While Loop: The while loop is used to execute a block of code as long as a specified condition is true.
Syntax:
“`php
while (condition) {
// code to be executed
}
“`
Example:
“`php
$i = 0;
while ($i < 5) {
echo "The value of i is: " . $i . "
“;
$i++;
}
“`
Output:
“`
The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
“`
3. Do-While Loop: The do-while loop is a variant of the while loop. It will execute a block of code once before checking if the condition is true, and then repeat the loop as long as the condition is true.
Syntax:
“`php
do {
// code to be executed
} while (condition);
“`
Example:
“`php
$i = 0;
do {
echo “The value of i is: ” . $i . “
“;
$i++;
} while ($i < 5);
```
Output:
```
The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
```
4. Foreach Loop: The foreach loop is used to iterate over arrays or objects.
Syntax:
```php
foreach ($array as $value) {
// code to be executed
}
```
Example:
```php
$fruits = array("apple", "banana", "orange");
foreach ($fruits as $fruit) {
echo "I like " . $fruit . "
“;
}
“`
Output:
“`
I like apple
I like banana
I like orange
“`