The best examples of learn PHP arrays and loops with practical examples

If you’re trying to get comfortable with PHP, nothing beats seeing real code in action. This guide is packed with the best examples of learn PHP arrays and loops with practical examples, written for people who want to understand *why* the code works, not just copy and paste it. We’ll walk through real examples you might actually use in 2024 and 2025: shopping carts, user lists, simple reports, and even a tiny API-style response. These examples of PHP arrays and loops are written in plain English, with comments and step-by-step explanations so you can follow along even if you’re just getting started. By the end, you’ll know how to create arrays, loop through them with `for`, `foreach`, `while`, and `do…while`, and combine them in ways that feel natural and reusable. Keep your editor open; you’ll want to tweak these examples and make them your own as you read.
Written by
Taylor
Published

Quick real-world examples of PHP arrays and loops

Let’s start with a few tiny, realistic snippets. These examples of learn PHP arrays and loops with practical examples are the kind of things you might actually write on a small project.

Example of looping through a shopping cart

$cart = [
    'Apple' => 1.49,
    'Bread' => 2.99,
    'Milk'  => 3.25,
];

$total = 0;

foreach (\(cart as \)item => $price) {
    echo "Item: \(item | Price: $\)price\n";
    \(total += \)price;
}

echo "Total: $$total\n";

Here, the array stores product names and prices. The foreach loop walks through each key/value pair, prints it, and builds up a total. This is one of the best examples of how arrays and loops work together in a way that mirrors real life: a list of items and a running sum.

Example of looping through users from a database (simulated)

$users = [
    ['id' => 1, 'name' => 'Alex',  'active' => true],
    ['id' => 2, 'name' => 'Jamie', 'active' => false],
    ['id' => 3, 'name' => 'Riley', 'active' => true],
];

foreach (\(users as \)user) {
    if ($user['active']) {
        echo $user['name'] . " is active.\n";
    }
}

This example of combining arrays and loops is very close to what you’d do after fetching rows from a database with PDO or MySQLi.


Why arrays and loops matter in modern PHP (2024–2025)

PHP still powers a huge chunk of the web, including WordPress, Laravel apps, and plenty of internal tools. Arrays and loops sit at the center of almost everything you do in PHP:

  • Handling JSON responses from APIs
  • Managing form submissions
  • Processing CSV or log files
  • Building dashboards and admin panels

Even in 2024–2025, as frameworks and tools evolve, the examples of learn PHP arrays and loops with practical examples you’ll see here map directly to what you’d do in Laravel controllers, WordPress plugins, or small standalone scripts.

If you’re curious about how widely PHP is used, you can compare it to other languages through resources like the Harvard CS50 materials (which discuss multiple languages and web development patterns) or language popularity indexes from universities and research groups.


Basic array examples: indexed and associative

Before we layer on loops, let’s ground ourselves in a few simple array examples. These are the building blocks for the more advanced real examples later.

Indexed array of temperatures

$temperaturesF = [72, 68, 75, 70];

for (\(i = 0; \)i < count(\(temperaturesF); \)i++) {
    echo "Day " . (\(i + 1) . ": " . \)temperaturesF[$i] . "°F\n";
}

Here you see a classic for loop. It uses an index ($i) to walk through the array. This pattern shows up when you care about the position of an item (for example, “Day 1, Day 2, Day 3…”).

Associative array of user profile data

$profile = [
    'name'  => 'Taylor',
    'email' => 'taylor@example.com',
    'role'  => 'admin',
];

foreach (\(profile as \)field => $value) {
    echo ucfirst(\(field) . ': ' . \)value . "\n";
}

This is a clean example of how associative arrays pair nicely with foreach. The examples include printing settings, configuration values, or labels and values in a profile page.


Practical examples of learn PHP arrays and loops with real data

Now let’s push beyond toy snippets. The next examples of learn PHP arrays and loops with practical examples feel like code you might commit to a real project.

1. Building a simple report from sales data

Imagine you have daily sales figures for a week and you want a quick summary.

$sales = [
    'Monday'    => 150.25,
    'Tuesday'   => 200.10,
    'Wednesday' => 175.75,
    'Thursday'  => 220.00,
    'Friday'    => 310.40,
];

$totalSales = 0;
$highestDay = '';
$highestAmount = 0;

foreach (\(sales as \)day => $amount) {
    echo "\(day: $\)amount\n";

    \(totalSales += \)amount;

    if (\(amount > \)highestAmount) {
        \(highestAmount = \)amount;
        \(highestDay = \)day;
    }
}

echo "\nTotal sales: $$totalSales\n";
echo "Best day: \(highestDay with $\)highestAmount\n";

This one snippet gives you a total and the best-performing day. It’s a strong example of how loops let you compute aggregates from arrays.

2. Filtering invalid email addresses from a list

User-submitted data is messy. Arrays plus loops help you clean it up.

$emails = [
    'valid@example.com',
    'not-an-email',
    'user@domain',
    'hello@site.com',
];

$validEmails = [];

foreach (\(emails as \)email) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        \(validEmails[] = \)email;
    }
}

print_r($validEmails);

This reflects a real pattern in 2024–2025 web apps: validating input, pushing the good data into a new array, and ignoring the rest. PHP’s filter_var function is documented thoroughly in the PHP manual, which is still one of the best authoritative references for language features.

3. Generating an HTML dropdown from an array

You’ll often turn arrays into HTML. Here’s a small but very practical example.

$states = ['CA', 'NY', 'TX', 'FL'];

echo "<select name=\"state\">";

foreach (\(states as \)state) {
    echo "<option value=\"\(state\">\)state</option>";
}

echo "</select>";

This is one of the best examples of arrays powering your UI. The moment your list of options comes from a database, this pattern becomes even more valuable.

4. Using while to read lines from a file

Sometimes you don’t have a full array yet; you build it as you loop.

$handle = fopen('log.txt', 'r');
$errors = [];

if ($handle) {
    while ((\(line = fgets(\)handle)) !== false) {
        if (strpos($line, 'ERROR') !== false) {
            \(errors[] = trim(\)line);
        }
    }

    fclose($handle);
}

print_r($errors);

This shows a different style: the loop creates the array as it goes. It’s a real example of how you’d process server logs or import data.

5. Combining arrays and loops for a tiny API-style response

APIs often return JSON. PHP arrays map naturally to JSON objects and lists.

$tasks = [
    ['id' => 1, 'title' => 'Write report', 'completed' => false],
    ['id' => 2, 'title' => 'Fix bug #42', 'completed' => true],
    ['id' => 3, 'title' => 'Email client', 'completed' => false],
];

$pending = [];

foreach (\(tasks as \)task) {
    if (! $task['completed']) {
        \(pending[] = \)task;
    }
}

header('Content-Type: application/json');
echo json_encode([
    'pending_count' => count($pending),
    'pending_tasks' => $pending,
]);

This is one of the best examples of learn PHP arrays and loops with practical examples if you’re eyeing API or backend work.


Nested loops with multidimensional arrays

Sooner or later, you hit data that looks like a table: rows and columns. That’s where nested loops and multidimensional arrays come in.

Example of a class gradebook

$students = [
    [
        'name'   => 'Alex',
        'grades' => [88, 92, 79],
    ],
    [
        'name'   => 'Jordan',
        'grades' => [95, 90, 93],
    ],
];

foreach (\(students as \)student) {
    $sum = 0;

    foreach (\(student['grades'] as \)grade) {
        \(sum += \)grade;
    }

    \(average = \)sum / count($student['grades']);

    echo \(student['name'] . ' average: ' . round(\)average, 1) . "\n";
}

This nested foreach pattern shows up everywhere: e‑commerce orders with order lines, blog posts with comments, survey responses with answers. It’s one of the most reusable examples of learn PHP arrays and loops with practical examples you can study.

If you’re interested in how data structures like this are taught more formally, universities like MIT and Harvard publish free course materials that talk about arrays, lists, and loops across multiple languages.


Common mistakes and how to avoid them

As you experiment with these examples of PHP arrays and loops, a few problems pop up over and over. Here’s how to sidestep them.

Off-by-one errors with for loops

$items = ['a', 'b', 'c'];

// Buggy: uses <= instead of <
for (\(i = 0; \)i <= count(\(items); \)i++) {
    echo \(items[\)i] . "\n"; // Last iteration: undefined index
}

Fix it by using < instead of <=, or by caching the length:

\(length = count(\)items);

for (\(i = 0; \)i < \(length; \)i++) {
    echo \(items[\)i] . "\n";
}

Accidentally modifying arrays by reference

$numbers = [1, 2, 3];

foreach (\(numbers as &\)n) {
    $n *= 2;
}

// Always unset the reference
unset($n);

If you forget unset($n);, that reference can leak into later code and cause confusing behavior. For most beginners, skipping & entirely is safer until you truly need it.


Putting it together: a mini “user dashboard” script

To wrap up, here’s a slightly longer script that pulls together many of the patterns from our examples of learn PHP arrays and loops with practical examples.

Scenario: you have users, each with login attempts. You want to:

  • Print each user
  • Count failed logins
  • Flag users with too many failures
$users = [
    [
        'name'    => 'Alex',
        'logins'  => [
            ['success' => true],
            ['success' => false],
            ['success' => true],
        ],
    ],
    [
        'name'    => 'Jordan',
        'logins'  => [
            ['success' => false],
            ['success' => false],
            ['success' => false],
        ],
    ],
];

$lockThreshold = 3;

foreach (\(users as \)user) {
    $failed = 0;

    foreach (\(user['logins'] as \)login) {
        if (! $login['success']) {
            $failed++;
        }
    }

    echo \(user['name'] . ' failed logins: ' . \)failed;

    if (\(failed >= \)lockThreshold) {
        echo " (LOCK ACCOUNT)";
    }

    echo "\n";
}

This is a real example of how you might implement a simple security check. While security itself is a bigger topic (the NIST site is a solid reference for security guidelines), the array-and-loop logic here is the same pattern you’d use in more advanced systems.


FAQ: examples of PHP arrays and loops

What are some common examples of PHP arrays and loops in everyday projects?

Common examples of arrays and loops include:

  • Iterating over products in a shopping cart to calculate totals
  • Looping through form submissions to validate fields
  • Reading rows from a CSV file into an array and summarizing the data
  • Filtering user lists, like active vs inactive accounts

All of these mirror the best examples of learn PHP arrays and loops with practical examples shown earlier.

Can I mix different loop types (for, foreach, while) with the same array?

Yes. You can iterate the same array with any loop type. In practice, foreach is usually the cleanest for arrays, while for is handy when you care about numeric indexes, and while fits streaming data (files, network responses). The examples include each style so you can see where each one shines.

Is foreach faster than for in PHP?

For most small to medium workloads, the performance difference is not worth worrying about. foreach tends to be more readable when working with arrays, which is why you see it in so many real examples. When performance truly matters, profiling tools and the official PHP documentation can guide you better than guesswork.

Where can I practice more examples of PHP arrays and loops?

You can:

  • Rebuild the best examples here with your own data (movies, expenses, tasks)
  • Use online judges and coding practice sites that support PHP
  • Follow along with university-style exercises from places like Harvard CS50 or MIT OpenCourseWare, adapting array and loop tasks into PHP

The key is repetition: take each example of an array-and-loop pattern and twist it slightly until it feels natural.


You don’t have to memorize every syntax detail right away. Keep this collection of examples of learn PHP arrays and loops with practical examples nearby, copy a snippet that feels close to what you need, and then reshape it. That’s how most real developers work—and it’s a very effective way to learn.

Explore More PHP Code Snippets

Discover more examples and insights in this category.

View All PHP Code Snippets