PHP Loops for Kids and Beginners: for, while and foreach — Part 7

Loops are used when we want PHP to repeat an instruction.

Instead of writing the same code five, ten or even one hundred times, we can write it once and tell PHP how many times to repeat it.

In Part 7 of this PHP tutorial for kids and beginners, you will learn:

  • What a loop is
  • Why programmers use loops
  • How to create a for loop
  • How to use a while loop
  • How a do...while loop works
  • How to use foreach with arrays
  • How to stop or skip part of a loop
  • How to avoid an infinite loop
  • How to build a multiplication-table project

All the examples use beginner-friendly PHP 8 syntax.


Quick Answer

A PHP loop repeats a block of code.

For example:

<?php

for ($number = 1; $number <= 5; $number++) {
    echo $number . "<br>";
}

The output is:

1
2
3
4
5

PHP repeats the echo instruction until $number becomes greater than 5.


What Is a Loop?

Imagine that a teacher asks you to write:

I will practise PHP.

five times.

Without a loop, you might write:

<?php

echo "I will practise PHP.<br>";
echo "I will practise PHP.<br>";
echo "I will practise PHP.<br>";
echo "I will practise PHP.<br>";
echo "I will practise PHP.<br>";

This works, but it repeats the same instruction many times.

With a loop, we can write:

<?php

for ($count = 1; $count <= 5; $count++) {
    echo "I will practise PHP.<br>";
}

Both examples produce the same result.

The loop is shorter and easier to change. If we want the message to appear 100 times, we only need to change 5 to 100.


The Main PHP Loops

PHP provides several types of loops.

LoopBest used when
forYou know how many times to repeat something
whileRepeat while a condition remains true
do...whileRun the code once before checking the condition
foreachGo through the items in an array

You do not need to memorise everything immediately. Try each example and change the values to see what happens.


1. The PHP for Loop

A for loop is useful when we know how many times something should repeat.

Here is a basic example:

<?php

for ($number = 1; $number <= 5; $number++) {
    echo "Number: " . $number . "<br>";
}

The output is:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

A for loop has three important parts:

for (starting_value; condition; change) {
    // Code to repeat
}

In our example:

for ($number = 1; $number <= 5; $number++)

This means:

PartCodeMeaning
Starting value$number = 1Begin counting at 1
Condition$number <= 5Continue while the number is 5 or less
Change$number++Add 1 after every round

The characters ++ mean “increase by one”.

This:

$number++;

is similar to:

$number = $number + 1;

Counting Backwards

A loop can also count backwards.

<?php

for ($number = 5; $number >= 1; $number--) {
    echo $number . "<br>";
}

echo "Blast off!";

The output is:

5
4
3
2
1
Blast off!

The characters -- reduce the value by one after each round.


Counting in Twos

We do not always need to add one.

<?php

for ($number = 2; $number <= 10; $number += 2) {
    echo $number . "<br>";
}

The output is:

2
4
6
8
10

The code:

$number += 2;

means:

$number = $number + 2;

We can use this to display even numbers.


Displaying Odd Numbers

Start at 1 and increase the number by 2:

<?php

for ($number = 1; $number <= 10; $number += 2) {
    echo $number . "<br>";
}

The output is:

1
3
5
7
9

Using a for Loop with HTML

PHP can use a loop to create HTML elements.

<!DOCTYPE html>
<html>
<head>
    <title>My PHP List</title>
</head>
<body>

<h1>Five Stars</h1>

<?php

for ($star = 1; $star <= 5; $star++) {
    echo "<p>⭐ Star " . $star . "</p>";
}

?>

</body>
</html>

PHP produces five HTML paragraphs.

This is one reason loops are useful in website development. They can generate lists, table rows, cards, menus and other repeated elements.


2. The PHP while Loop

A while loop continues running while its condition is true.

<?php

$score = 1;

while ($score <= 5) {
    echo "Score: " . $score . "<br>";
    $score++;
}

The output is:

Score: 1
Score: 2
Score: 3
Score: 4
Score: 5

The loop works like this:

  1. $score starts at 1.
  2. PHP checks whether $score <= 5.
  3. If the condition is true, PHP runs the code inside the loop.
  4. $score++ increases the score by one.
  5. PHP checks the condition again.
  6. The loop stops when the score becomes 6.

When Should We Use while?

Use a while loop when the number of repetitions depends on a condition.

For example, imagine that a game character starts with 5 energy points:

<?php

$energy = 5;

while ($energy > 0) {
    echo "The player has " . $energy . " energy left.<br>";
    $energy--;
}

echo "The player needs to rest.";

The loop continues while the player has energy.

The output is:

The player has 5 energy left.
The player has 4 energy left.
The player has 3 energy left.
The player has 2 energy left.
The player has 1 energy left.
The player needs to rest.

Be Careful with Infinite Loops

An infinite loop never stops.

This code is incorrect:

<?php

$number = 1;

while ($number <= 5) {
    echo $number;
}

The value of $number never changes. It remains 1, so the condition is always true.

The corrected version is:

<?php

$number = 1;

while ($number <= 5) {
    echo $number . "<br>";
    $number++;
}

Always check that something inside a while loop will eventually make its condition false.

If you accidentally run an infinite loop using PHP’s development server, stop the server with Ctrl + C.


3. The PHP do…while Loop

A do...while loop is similar to a while loop.

The important difference is that a do...while loop runs its code before checking the condition.

<?php

$number = 1;

do {
    echo "Number: " . $number . "<br>";
    $number++;
} while ($number <= 5);

The output is:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Notice the semicolon here:

} while ($number <= 5);

It is required at the end of a do...while loop.


while Compared with do…while

Consider this while loop:

<?php

$number = 10;

while ($number <= 5) {
    echo $number;
}

Nothing is displayed because the condition is false before the loop begins.

Now try a do...while loop:

<?php

$number = 10;

do {
    echo $number;
} while ($number <= 5);

The output is:

10

The code runs once before PHP checks the condition.

Use do...while when an instruction must happen at least once.


4. The PHP foreach Loop

The foreach loop is designed for arrays.

Suppose we have an array containing several fruits:

<?php

$fruits = [
    "Apple",
    "Banana",
    "Orange",
    "Mango"
];

We can display every fruit with:

<?php

$fruits = [
    "Apple",
    "Banana",
    "Orange",
    "Mango"
];

foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}

The output is:

Apple
Banana
Orange
Mango

During each round, PHP places the current array item inside $fruit.

The loop works like this:

RoundValue of $fruit
1Apple
2Banana
3Orange
4Mango

PHP stops automatically after it reaches the final item.


Creating an HTML List with foreach

We can use foreach to build a proper HTML list.

<?php

$subjects = [
    "Mathematics",
    "Science",
    "English",
    "Computer Studies"
];

echo "<ul>";

foreach ($subjects as $subject) {
    echo "<li>" . $subject . "</li>";
}

echo "</ul>";

The browser displays:

  • Mathematics
  • Science
  • English
  • Computer Studies

A cleaner way is to combine PHP with HTML:

<?php

$subjects = [
    "Mathematics",
    "Science",
    "English",
    "Computer Studies"
];

?>

<h2>My Subjects</h2>

<ul>
    <?php foreach ($subjects as $subject): ?>
        <li><?php echo $subject; ?></li>
    <?php endforeach; ?>
</ul>

The alternative syntax:

foreach (...):

ends with:

endforeach;

This style can be easier to read when PHP is mixed with HTML.


foreach with Keys and Values

An associative array stores information using named keys.

<?php

$student = [
    "name" => "Aina",
    "age" => 13,
    "favourite_subject" => "Science"
];

We can access both the key and value:

<?php

$student = [
    "name" => "Aina",
    "age" => 13,
    "favourite_subject" => "Science"
];

foreach ($student as $key => $value) {
    echo $key . ": " . $value . "<br>";
}

The output is:

name: Aina
age: 13
favourite_subject: Science

In this loop:

foreach ($student as $key => $value)
  • $key contains the name of the array item.
  • $value contains its value.

A Better Student Profile

We can create friendly labels instead of displaying the original keys:

<?php

$student = [
    "Name" => "Aina",
    "Age" => 13,
    "Favourite Subject" => "Science"
];

foreach ($student as $label => $value) {
    echo "<strong>" . $label . ":</strong> ";
    echo $value . "<br>";
}

The result is:

Name: Aina
Age: 13
Favourite Subject: Science

5. Using break to Stop a Loop

The break command stops a loop immediately.

<?php

for ($number = 1; $number <= 10; $number++) {
    if ($number === 6) {
        break;
    }

    echo $number . "<br>";
}

The output is:

1
2
3
4
5

When $number becomes 6, PHP runs break and exits the loop.

This can be useful when PHP has already found the item it was searching for.


Searching an Array with break

<?php

$animals = [
    "Cat",
    "Rabbit",
    "Tiger",
    "Elephant"
];

foreach ($animals as $animal) {
    if ($animal === "Tiger") {
        echo "Tiger found!";
        break;
    }

    echo "Checking " . $animal . "...<br>";
}

The output is:

Checking Cat...
Checking Rabbit...
Tiger found!

PHP does not continue to the elephant because the loop has already stopped.


6. Using continue to Skip One Round

The continue command skips the remaining code in the current round and moves to the next one.

<?php

for ($number = 1; $number <= 5; $number++) {
    if ($number === 3) {
        continue;
    }

    echo $number . "<br>";
}

The output is:

1
2
4
5

PHP skips the echo instruction when the number is 3.

Unlike break, continue does not stop the complete loop.

CommandWhat it does
breakStops the entire loop
continueSkips the current round

7. Loops Inside Other Loops

A loop can be placed inside another loop. This is called a nested loop.

<?php

for ($row = 1; $row <= 3; $row++) {
    for ($column = 1; $column <= 3; $column++) {
        echo "Row " . $row;
        echo ", Column " . $column;
        echo "<br>";
    }
}

The output is:

Row 1, Column 1
Row 1, Column 2
Row 1, Column 3
Row 2, Column 1
Row 2, Column 2
Row 2, Column 3
Row 3, Column 1
Row 3, Column 2
Row 3, Column 3

For each row, the inner loop goes through all three columns.

Nested loops are useful for grids, calendars, game boards and HTML tables. However, too many large nested loops can make a program slow.


Mini Project 1: Build a Multiplication Table

Let us create a multiplication table for the number 5.

<!DOCTYPE html>
<html>
<head>
    <title>PHP Multiplication Table</title>
</head>
<body>

<h1>5 Times Table</h1>

<?php

$table = 5;

for ($number = 1; $number <= 12; $number++) {
    $answer = $table * $number;

    echo $table;
    echo " × ";
    echo $number;
    echo " = ";
    echo $answer;
    echo "<br>";
}

?>

</body>
</html>

The output begins with:

5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
5 × 4 = 20

It continues until:

5 × 12 = 60

Change:

$table = 5;

to:

$table = 9;

The program will create the 9 times table without requiring any other changes.


Mini Project 2: Multiplication Table with HTML

We can improve the project by displaying the results inside an HTML table.

<!DOCTYPE html>
<html>
<head>
    <title>Multiplication Table</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 30px;
        }

        table {
            border-collapse: collapse;
            width: 400px;
        }

        th,
        td {
            border: 1px solid #333;
            padding: 10px;
            text-align: center;
        }

        th {
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>

<?php $table = 7; ?>

<h1><?php echo $table; ?> Times Table</h1>

<table>
    <tr>
        <th>Calculation</th>
        <th>Answer</th>
    </tr>

    <?php for ($number = 1; $number <= 12; $number++): ?>
        <tr>
            <td>
                <?php
                echo $table . " × " . $number;
                ?>
            </td>

            <td>
                <?php
                echo $table * $number;
                ?>
            </td>
        </tr>
    <?php endfor; ?>
</table>

</body>
</html>

Save the file as:

multiplication-table.php

If you are using PHP’s built-in development server, open the project folder in a terminal and run:

php -S localhost:8000

Then visit:

http://localhost:8000/multiplication-table.php

Mini Project 3: Simple Game Leaderboard

This project uses an associative array and a foreach loop.

<!DOCTYPE html>
<html>
<head>
    <title>Game Leaderboard</title>
</head>
<body>

<h1>Game Leaderboard</h1>

<?php

$players = [
    "Aiman" => 950,
    "Mei Ling" => 870,
    "Kumar" => 820,
    "Sarah" => 760
];

$position = 1;

?>

<ol>
    <?php foreach ($players as $name => $score): ?>
        <li>
            <?php
            echo $name;
            echo " — ";
            echo $score;
            echo " points";
            ?>
        </li>

        <?php $position++; ?>
    <?php endforeach; ?>
</ol>

</body>
</html>

The browser displays a numbered list of players and their scores.

The program can display more players simply by adding them to the array.


Common PHP Loop Mistakes

1. Forgetting to Change the Counter

Incorrect:

<?php

$number = 1;

while ($number <= 10) {
    echo $number;
}

The value never changes, causing an infinite loop.

Correct:

<?php

$number = 1;

while ($number <= 10) {
    echo $number . "<br>";
    $number++;
}

2. Using the Wrong Comparison

This loop:

for ($number = 1; $number < 5; $number++) {
    echo $number . "<br>";
}

stops at 4 because the condition requires the number to be lower than 5.

To include 5, use:

$number <= 5

Remember:

OperatorMeaning
<Less than
<=Less than or equal to
>Greater than
>=Greater than or equal to
===Exactly equal in value and type
!==Not exactly equal

3. Adding a Semicolon After the Loop

Incorrect:

for ($number = 1; $number <= 5; $number++); {
    echo $number;
}

The semicolon ends the loop too early.

Correct:

for ($number = 1; $number <= 5; $number++) {
    echo $number;
}

4. Forgetting the Curly Braces

PHP allows some one-line loops without curly braces, but beginners should keep them.

Recommended:

foreach ($animals as $animal) {
    echo $animal;
}

Curly braces make the beginning and end of the repeated code clear.


5. Changing an Array Unexpectedly

Be careful when changing an array while looping through it. Removing or adding elements during a loop can produce confusing results.

For beginner projects, prepare the array first and then use foreach to display or process its values.


Practice Exercises

Try completing these exercises without copying the final answer immediately.

Exercise 1: Count from 1 to 20

Create a for loop that displays the numbers from 1 to 20.

Expected result:

1 2 3 4 5 ... 20

Exercise 2: Count Backwards

Create a loop that counts from 10 down to 1 and then displays:

Happy New Year!

Exercise 3: Even Numbers

Display all the even numbers between 2 and 20.

Exercise 4: Favourite Foods

Create an array containing five foods. Use foreach to display each food inside an HTML list.

Exercise 5: Total the Scores

Use this array:

$scores = [10, 20, 15, 25, 30];

Create a loop that adds all the scores together.

Hint:

$total = 0;

Exercise 6: Multiplication Table

Change the multiplication-table project so that it displays the 12 times table.


Exercise Answers

Answer 1

<?php

for ($number = 1; $number <= 20; $number++) {
    echo $number . " ";
}

Answer 2

<?php

for ($number = 10; $number >= 1; $number--) {
    echo $number . "<br>";
}

echo "Happy New Year!";

Answer 3

<?php

for ($number = 2; $number <= 20; $number += 2) {
    echo $number . "<br>";
}

Answer 4

<?php

$foods = [
    "Nasi lemak",
    "Chicken rice",
    "Roti canai",
    "Fried noodles",
    "Pizza"
];

echo "<ul>";

foreach ($foods as $food) {
    echo "<li>" . $food . "</li>";
}

echo "</ul>";

Answer 5

<?php

$scores = [10, 20, 15, 25, 30];

$total = 0;

foreach ($scores as $score) {
    $total += $score;
}

echo "Total score: " . $total;

The output is:

Total score: 100

Answer 6

Change the table number:

$table = 12;

The existing loop can remain the same.


PHP Loop Cheat Sheet

// for loop
for ($number = 1; $number <= 5; $number++) {
    echo $number;
}
// while loop
$number = 1;

while ($number <= 5) {
    echo $number;
    $number++;
}
// do...while loop
$number = 1;

do {
    echo $number;
    $number++;
} while ($number <= 5);
// foreach loop
$colours = ["Red", "Blue", "Green"];

foreach ($colours as $colour) {
    echo $colour;
}
// foreach with keys and values
$student = [
    "name" => "Ali",
    "age" => 13
];

foreach ($student as $key => $value) {
    echo $key . ": " . $value;
}

Frequently Asked Questions

Which PHP loop should a beginner learn first?

Start with the for loop because its starting value, condition and counter are shown together. After that, learn while and foreach.

When should I use foreach?

Use foreach when you want to process every item in an array. It is normally easier than using a numbered for loop for this purpose.

What is an infinite loop?

An infinite loop is a loop whose stopping condition never becomes false. It continues until the program is stopped or PHP reaches a configured resource limit.

What is the difference between while and do…while?

A while loop checks its condition before running. A do...while loop runs once before checking its condition.

Therefore, a do...while loop always runs at least once.

What does $number++ mean?

It increases the value of $number by one.

$number++;

is similar to:

$number = $number + 1;

Can PHP loops create HTML?

Yes. PHP loops are commonly used to generate HTML lists, tables, menus, cards and other repeated webpage elements.

Can a loop contain an if statement?

Yes. Conditions are frequently placed inside loops.

for ($number = 1; $number <= 10; $number++) {
    if ($number % 2 === 0) {
        echo $number . " is even.<br>";
    }
}

Can one loop be placed inside another?

Yes. This is called a nested loop. It is useful for tables and grids, but large nested loops can require more processing.


Final Summary

A loop allows PHP to repeat instructions without duplicating code.

In this tutorial, we learned:

  • for repeats code using a counter.
  • while continues while a condition is true.
  • do...while runs at least once.
  • foreach processes the items in an array.
  • break stops a loop.
  • continue skips the current round.
  • A loop must eventually reach its stopping condition.
  • Loops can generate HTML lists and tables.
  • Nested loops can create rows, columns and grids.

The best way to understand loops is to edit the examples. Change the starting number, stopping condition and counter, then observe how the output changes.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *