Learn to Code via Tutorials on Repl.it

← Back to all posts
1
PHP Tutorial No. 4: Loops
h
malvoliothegood (90)

PHP Tutorial No. 4: Loops

Reference: Control Structures

for loops

Read the following: Reference: for loops

Often it is necessary to repeat an action. For example, iterate or loop through an array and display it's contents. For example the for loop below is used to display favourite foods in an unordered list.

$fav_foods = ["fries", "pizza", "nachos", "sushi", "burgers"];

echo "<h1>My Favourite Foods</h1>";

echo "<ul>";

for ($counter = 0; $counter < count($fav_foods); $counter += 1) {
    echo "<li>" . $fav_foods[] . "</li>";
}

echo "</ul>";

Note the use of the count function. It returns the number of items in the $fav_foods array.

foreach loops

Read the following: Reference: foreach

foreach loops are used to iterate through associative arrays. The following code illustrates this. The array uses key/value pairs to store food names and ratings (1 excellent, 4 average). So pizza and sushi come out tops.

$fav_foods = ["fries" => 1, "pizza" => 3, "nachos" => 4, "sushi" => 1, "burgers" => 2];

echo "<h1>My Favourite Foods and their Ratings</h1>";

echo "<ul>";

foreach ($fav_foods as $food => $rating) {
    echo "<li>" . $food . ",  " . $rating . "</li>";
}

echo "</ul>";

Link to repl

while loops

Read the following: Reference: while

while loops can be use instead of for loops. Below is the for loop example code rewritten to use while.

$fav_foods = ["fries", "pizza", "nachos", "sushi", "burgers"];

echo "<h1>My Favourite Foods</h1>";

$counter = 0;
$num_foods = count($fav_foods);

echo "<ul>";
while ($counter < $num_foods) {
    echo "<li>" . $fav_foods[] . "</li>";
    $counter += 1;
}
echo "</ul>";

Previous section in the tutorial: Decisions