Back to Blog
Lesson 10 of the PHP: Modern PHP from the Ground Up course
PHPJuly 28, 20264 min read

Mastering Foreach Loops: Efficient Array Iteration in PHP

Learn how to use PHP foreach loops to traverse arrays, access keys and values, and modify data. Master the most essential tool for modern PHP iteration.

PHPforeacharray iterationloopsprogramming basics
Close-up of PHP code on a monitor, highlighting development and programming concepts.

Previously in this course, we explored Iterating with For and While Loops in PHP, where we learned to control loop execution manually. While for and while loops are useful for counting or conditional repetition, they are often overkill for simple array traversal.

In this lesson, we master the foreach loop—the idiomatic, clean, and safe way to handle collection iteration in PHP.

Why Foreach is the Industry Standard

Unlike for loops, which require you to track an index variable and check the array count, foreach is purpose-built for collections. It automatically handles the internal pointer of the array, meaning you don't have to worry about "off-by-one" errors or managing counter variables.

If you have an array, foreach is almost always the correct choice for reading its contents.

Basic Syntax for Value Access

The most common use case is simply iterating over a list of values.

PHP
$fruits = ['Apple', 'Banana', 'Cherry'];

foreach ($fruits as $fruit) {
    echo "I love eating: " . $fruit . PHP_EOL;
}

In this snippet, $fruits is our source array. The variable $fruit is a temporary handle that points to the current element in the loop. PHP handles the heavy lifting of moving to the next item automatically.

Accessing Both Keys and Values

In Introduction to PHP Arrays, we learned about associative arrays. Often, you need the key (like an ID or a label) alongside the value.

You use the => operator within the foreach declaration to capture the key:

PHP
$userRoles = [
    'admin'  => 'Alice',
    'editor' => 'Bob',
    'viewer' => 'Charlie'
];

foreach ($userRoles as $role => $name) {
    echo "The {$role} is {$name}." . PHP_EOL;
}

Modifying Array Data During Iteration

Detailed view of programming code in a dark theme on a computer screen.

One of the most powerful features of foreach is the ability to modify the array elements in place using references. If you prefix the value variable with an ampersand (&), you gain write access to the original array.

PHP
$prices = [10, 20, 30];

#6A9955">// Add a 10% tax to every price
foreach ($prices as &$price) {
    $price = $price * 1.10;
}

#6A9955">// Crucial: Unset the reference after use
unset($price);

print_r($prices);

Note: Always use unset() on the reference variable after the loop. If you don't, the variable $price remains bound to the last element of the array, which can lead to accidental data corruption if you reuse that variable later in your code.

Hands-on Exercise

In your running project, locate the array containing your navigation menu items (or create one if you haven't yet). Use a foreach loop to iterate through this array and print an HTML <li> tag for each item.

  1. Define an associative array where the key is the URL and the value is the link label.
  2. Use foreach ($pages as $url => $label) to build the HTML string.
  3. Echo the result to your browser.

Common Pitfalls

  • Modifying without Reference: If you try to change $value inside a standard foreach loop without the &, you are only changing a local copy. The original array remains untouched.
  • The "Dangling Reference": As mentioned above, failing to unset() a reference variable after a loop is a classic source of "why is my data changing unexpectedly?" bugs.
  • Skipping Keys: Don't try to use a for loop to iterate over an associative array; it won't work because associative keys aren't necessarily sequential integers. Stick to foreach for safety.

FAQ

Q: Can I use break and continue inside a foreach loop? A: Yes. Just like in for and while loops, break will exit the iteration entirely, and continue will skip the current element and move to the next one.

Q: Is foreach slower than for? A: For standard arrays, the difference is negligible. The readability and safety benefits of foreach far outweigh any theoretical micro-optimization.

Q: Does foreach work on multidimensional arrays? A: Yes, but you will need a nested foreach loop to access the inner elements. We covered the structure of these arrays in Multidimensional Arrays: Mastering Nested Data.

Recap

foreach is the gold standard for array iteration in PHP. You now know how to:

  1. Traverse indexed and associative arrays cleanly.
  2. Extract both keys and values.
  3. Safely modify array data using references.

Up next: We will shift gears to encapsulate this logic into reusable blocks by Defining Custom Functions.

Similar Posts