create a loop in php

There are four types of loops in PHP: while, for, foreach, and do-while.

While Loop

The while loop will execute a block of code as long as the specified condition is true.

main.php
while (condition) {
   // block of code to be executed
}
57 chars
4 lines

Example:

main.php
$i = 1;
while ($i <= 5) {
    echo $i;
    $i++;
}
51 chars
6 lines

Output:

main.php
12345
6 chars
2 lines

For Loop

The for loop is used when you know beforehand how many times the script should run.

main.php
for (initialization; condition; increment) {
    // block of code to be executed
}
83 chars
4 lines

Example:

main.php
for ($i = 1; $i <= 5; $i++) {
    echo $i;
}
45 chars
4 lines

Output:

main.php
12345
6 chars
2 lines

Foreach Loop

The foreach loop is used to iterate over arrays.

main.php
foreach ($array as $value) {
    // block of code to be executed
}
67 chars
4 lines

Example:

main.php
$colors = array("red", "green", "blue");

foreach ($colors as $value) {
    echo $value;
}
91 chars
6 lines

Output:

main.php
redgreenblue
13 chars
2 lines

Do-While Loop

The do-while loop will always execute the block of code at least once, even if the condition is false.

main.php
do {
    // block of code to be executed
} while (condition);
62 chars
4 lines

Example:

main.php
$i = 1;
do {
    echo $i;
    $i++;
} while ($i <= 5);
55 chars
6 lines

Output:

main.php
12345
6 chars
2 lines

gistlibby LogSnag