What is PHP Looping? Basic Overview and Role

Looping is used when you want to repeat the same process multiple times in a program. For example, it’s useful when you want to sequentially display numbers from 1 to 10 or process the contents of an array one by one.

Why is Looping Necessary?

Writing the same code multiple times manually is inefficient and increases the chance of mistakes. Using loops allows you to repeat with a single code multiple times, resulting in concise and maintainable programs.


Common Types of Loops in PHP (for, while, foreach)

1. for Loop

Use this when you want to repeat a process a fixed number of times. This code displays numbers sequentially from 1 to 5. It starts with $i = 1, repeats while $i <= 5, and increments $i++ by 1 each time.

for ($i = 1; $i <= 5; $i++) {
    echo "Current count is {$i}.<br>";
}

→ This example displays numbers from 1 to 5.

2. while Loop

The loop continues while the condition is true. This code loops while $i is 5 or less, displaying numbers from 1 to 5. The loop ends once the condition is no longer met.

$i = 1;
while ($i <= 5) {
    echo "while loop count: {$i}<br>";
    $i++;
}
// while loop count: 1
// while loop count: 2
// while loop count: 3
// while loop count: 4
// while loop count: 5

3. foreach Loop

Use this when you want to process elements in an array one by one. This code takes the contents of the array “red,” “blue,” and “green” sequentially and displays each.

$colors = ["red", "blue", "green"];
foreach ($colors as $color) {
    echo "The color is {$color}.<br>";
}
// The color is red.
// The color is blue.
// The color is green.

How to Use for Loops with Examples: From Basic to Advanced

Basic Example

for ($i = 0; $i < 3; $i++) {
    echo "Loop number: $i<br>";
}
// Loop number: 0
// Loop number: 1
// Loop number: 2

Advanced Example: Creating a Multiplication Table

for ($i = 1; $i <= 9; $i++) {
    for ($j = 1; $j <= 9; $j++) {
        echo "{$i} × {$j} = " . ($i * $j) . " ";
    }
    echo "<br>";
}
// 1 × 1 = 1 1 × 2 = 2 1 × 3 = 3 1 × 4 = 4 1 × 5 = 5 1 × 6 = 6 1 × 7 = 7 1 × 8 = 8 1 × 9 = 9 
// 2 × 1 = 2 2 × 2 = 4 2 × 3 = 6 2 × 4 = 8 2 × 5 = 10 2 × 6 = 12 2 × 7 = 14 2 × 8 = 16 2 × 9 = 18 
// 3 × 1 = 3 3 × 2 = 6 3 × 3 = 9 3 × 4 = 12 3 × 5 = 15 3 × 6 = 18 3 × 7 = 21 3 × 8 = 24 3 × 9 = 27 
// 4 × 1 = 4 4 × 2 = 8 4 × 3 = 12 4 × 4 = 16 4 × 5 = 20 4 × 6 = 24 4 × 7 = 28 4 × 8 = 32 4 × 9 = 36 
// 5 × 1 = 5 5 × 2 = 10 5 × 3 = 15 5 × 4 = 20 5 × 5 = 25 5 × 6 = 30 5 × 7 = 35 5 × 8 = 40 5 × 9 = 45 
// 6 × 1 = 6 6 × 2 = 12 6 × 3 = 18 6 × 4 = 24 6 × 5 = 30 6 × 6 = 36 6 × 7 = 42 6 × 8 = 48 6 × 9 = 54 
// 7 × 1 = 7 7 × 2 = 14 7 × 3 = 21 7 × 4 = 28 7 × 5 = 35 7 × 6 = 42 7 × 7 = 49 7 × 8 = 56 7 × 9 = 63 
// 8 × 1 = 8 8 × 2 = 16 8 × 3 = 24 8 × 4 = 32 8 × 5 = 40 8 × 6 = 48 8 × 7 = 56 8 × 8 = 64 8 × 9 = 72 
// 9 × 1 = 9 9 × 2 = 18 9 × 3 = 27 9 × 4 = 36 9 × 5 = 45 9 × 6 = 54 9 × 7 = 63 9 × 8 = 72 9 × 9 = 81 
  • Uses nested for loops to display all multiplication from 1 to 9.
  • Uses two variables, $i and $j, to separate outer and inner processing.

Differences and Usage Between while and do-while Loops

Example of while Loop

$i = 1;
while ($i <= 5) {
    echo "while loop count: $i<br>";
    $i++;
}
// while loop count: 1
// while loop count: 2
// while loop count: 3
// while loop count: 4
// while loop count: 5
  • Repeats only while the condition is met.
  • The condition is checked before the loop, so if it is false initially, the process is never executed.

Example of do-while Loop

$i = 1;
do {
    echo "do-while loop count: $i<br>";
    $i++;
} while ($i <= 5);
// do-while loop count: 1
// do-while loop count: 2
// do-while loop count: 3
// do-while loop count: 4
// do-while loop count: 5
  • The process is always executed at least once.
  • The condition is checked after the loop.

Arrays and Loops: How to Use foreach Loops and Examples

Basic Array Processing

The array $fruits contains “apple,” “banana,” and “orange,” which are taken out in order and displayed as “Fruit: apple,” etc. The key point is that the foreach loop processes each element of the array one by one. This makes it easy to handle large amounts of data.

$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
    echo "Fruit: $fruit<br>";
}
// Fruit: apple
// Fruit: banana
// Fruit: orange

Associative Array Processing

An associative array manages data as pairs of “keys (names)” and “values (contents).” This code takes the “key” and “value” from the associative array $user one by one and displays them. For example, it outputs “Name is Taro Yamada.” The key point is that the foreach syntax can handle both keys and values. Associative arrays are convenient for managing data with meaningful labels like “name” or “age.”

$user = [
    "Name" => "Taro Yamada",
    "Age" => 28,
    "Occupation" => "Engineer"
];

foreach ($user as $key => $value) {
    echo "$key is $value.<br>";
}
// Name is Taro Yamada.
// Age is 28.
// Occupation is Engineer.

Example of Multidimensional Array

A multidimensional array is an array containing other arrays.
For example, it is used to manage multiple user information together. This code processes multiple associative arrays inside $users in order and displays each “name” and “age.”
Using multidimensional arrays lets you manage multiple related pieces of information together. Then with foreach, you extract each one and access the inner elements.

$users = [
    ["Name" => "Sato", "Age" => 25],
    ["Name" => "Suzuki", "Age" => 30],
    ["Name" => "Takahashi", "Age" => 22],
];

foreach ($users as $user) {
    echo "Name: " . $user["Name"] . ", Age: " . $user["Age"] . "<br>";
}
// Name: Sato, Age: 25
// Name: Suzuki, Age: 30
// Name: Takahashi, Age: 22

Tips for Looping: Things to Watch Out For and How to Write Efficiently

  • Beware of infinite loops
    If you forget to update variables, the loop will run forever. Always write code that changes the condition.
  • Keep processing light
    If you perform heavy processing inside loops repeatedly, the performance will slow down. If possible, move processing outside the loop.
  • Consider array size
    Looping over large arrays with foreach can take time, so limit array size or add break conditions as needed.
  • Make code readable
    Use meaningful variable names and avoid overly deep nesting.

Common Errors in PHP Loops and How to Fix Them

1. Infinite Loop

$i = 0;
while ($i < 5) {
    echo $i;
    // No $i++ causes an infinite loop
}

→ Always include variable updates like $i++ inside the while loop.

2. Accessing Undefined Array Keys

$colors = ["red", "blue"];
echo $colors[2]; // Accessing a non-existent key

→ Check if the key exists in the array before accessing.

if (isset($colors[2])) {
    echo $colors[2];
} else {
    echo "No color available";
}

3. Syntax Errors (e.g., Missing Semicolon)

for ($i = 0; $i < 5; $i++) {
    echo $i  // Missing semicolon
}

→ Don’t forget the semicolon ;. Always read error messages carefully.


4. Errors Caused by Type Mismatch

$i = "5";
if ($i < 10) { // PHP converts types automatically, but be careful with complex calculations
    echo "Less than 10";
}

→ Explicitly cast types to be safer when comparing strings and numbers.

$i = (int)$i;