</>
Skip to content
PHP lessons (34/49)

PHP — OOP

for loop

Execute code a known number of times:

<?php
for ($i = 0; $i < 5; $i++) {
    echo "Iteration $i\n";
}
// 0 1 2 3 4
?>

The for loop has three parts: initialization, condition, and increment. Each part can be empty:

<?php
// Infinite loop (use break to exit)
for (;;) {
    break; // Stops immediately
}
?>

while loop

Repeat while a condition remains true:

<?php
$count = 0;
while ($count < 5) {
    echo "Count: $count\n";
    $count++;
}
// 0 1 2 3 4
?>

The condition is checked before each iteration. If the condition is false from the start, the body never executes:

<?php
$x = 10;
while ($x < 5) {
    echo "This never prints";
}
?>

do-while loop

Execute the body first, then check the condition:

<?php
$count = 0;
do {
    echo "Count: $count\n";
    $count++;
} while ($count < 5);
// 0 1 2 3 4
?>

The body always executes at least once, even if the condition is false:

<?php
$number = 100;
do {
    echo "This prints once\n";
} while ($number < 5);
// Prints once despite the condition being false
?>

foreach loop

Iterate over arrays and iterables:

<?php
$fruits = ["Apple", "Banana", "Cherry"];

// Iterate values
foreach ($fruits as $fruit) {
    echo "$fruit\n";
}

// Iterate with keys
$person = ["name" => "Alice", "age" => 30, "city" => "NYC"];
foreach ($person as $key => $value) {
    echo "$key: $value\n";
}
?>

Modifying arrays with foreach

By default, foreach works on a copy of the array. Use & to modify the original:

<?php
$numbers = [1, 2, 3, 4, 5];

// This doesn't modify $numbers
foreach ($numbers as $num) {
    $num = $num * 2;
}
print_r($numbers); // [1, 2, 3, 4, 5]

// This does modify $numbers
foreach ($numbers as &$num) {
    $num = $num * 2;
}
unset($num); // Break the reference
print_r($numbers); // [2, 4, 6, 8, 10]
?>

break and continue

Control loop execution:

<?php
// break: exit the loop entirely
for ($i = 0; $i < 100; $i++) {
    if ($i == 5) {
        break; // Stop at 5
    }
    echo "$i ";
}
// 0 1 2 3 4

// continue: skip to the next iteration
for ($i = 0; $i < 10; $i++) {
    if ($i % 2 == 0) {
        continue; // Skip even numbers
    }
    echo "$i ";
}
// 1 3 5 7 9
?>

Nested loops

Loops inside loops for multi-dimensional data:

<?php
// Multiplication table
for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= 5; $j++) {
        echo str_pad($i * $j, 4);
    }
    echo "\n";
}
// 1   2   3   4   5
// 2   4   6   8   10
// 3   6   9   12  15
// 4   8   12  16  20
// 5   10  15  20  25
?>

Loop performance

Choose the right loop for your use case:

<?php
$largeArray = range(1, 1000000);

// foreach is faster for arrays (optimized internally)
$start = microtime(true);
foreach ($largeArray as $val) { /* ... */ }
$end = microtime(true);
echo "foreach: " . round(($end - $start) * 1000, 2) . "ms\n";

// for is faster for numeric sequences
$start = microtime(true);
for ($i = 0, $len = count($largeArray); $i < $len; $i++) { /* ... */ }
$end = microtime(true);
echo "for: " . round(($end - $start) * 1000, 2) . "ms\n";
?>

Common patterns

<?php
// Iterate with index
$colors = ["red", "green", "blue"];
for ($i = 0; $i < count($colors); $i++) {
    echo "$i: $colors[$i]\n";
}

// Filter array
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$evens = [];
foreach ($numbers as $num) {
    if ($num % 2 == 0) {
        $evens[] = $num;
    }
}
print_r($evens); // [2, 4, 6, 8, 10]

// Search array
$search = "banana";
$fruits = ["apple", "banana", "cherry"];
$found = false;
foreach ($fruits as $index => $fruit) {
    if ($fruit === $search) {
        $found = true;
        echo "Found at index $index\n";
        break;
    }
}
?>

Mini Practice

Write PHP code that:

  1. Uses a for loop to print numbers 1-20
  2. Uses a while loop to find the first number divisible by 7 greater than 50
  3. Uses foreach to iterate over an associative array of product prices
  4. Uses nested loops to iterate over a 2D array

Up Next

In the next lesson, you'll learn about Arrays — creating, accessing, and manipulating arrays.

Related Topics

Frequently Asked Questions about OOP

What is OOP in PHP?

OOP is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn OOP?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn OOP.

Why is OOP important in PHP?

OOP is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.