# PHP Loops

Loops are used to execute the same block of code again and again, as long as a certain condition is true.

---

## 1. While Loop
The `while` loop loops through a block of code as long as the specified condition is true.

```php
$x = 1;

while($x <= 5) {
  echo "The number is: $x <br>";
  $x++;
}
```

## 2. Do...While Loop
The `do...while` loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

```php
$x = 1;

do {
  echo "The number is: $x <br>";
  $x++;
} while ($x <= 5);
```

## 3. For Loop
The `for` loop is used when you know in advance how many times the script should run.

```php
for ($x = 0; $x <= 10; $x++) {
  echo "The number is: $x <br>";
}
```

## 4. Foreach Loop
The `foreach` loop works only on arrays, and is used to loop through each key/value pair in an array.

```php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
  echo "$value <br>";
}
```

[[programming/php/php]]