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.

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

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.
- Define an associative array where the key is the URL and the value is the link label.
- Use
foreach ($pages as $url => $label)to build the HTML string. - Echo the result to your browser.
Common Pitfalls
- Modifying without Reference: If you try to change
$valueinside a standardforeachloop 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
forloop to iterate over an associative array; it won't work because associative keys aren't necessarily sequential integers. Stick toforeachfor 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:
- Traverse indexed and associative arrays cleanly.
- Extract both keys and values.
- Safely modify array data using references.
Up next: We will shift gears to encapsulate this logic into reusable blocks by Defining Custom Functions.
Work with me

Laravel SaaS MVP & Multi-Tenant App Development
Launch your SaaS MVP on Laravel — multi-tenant, subscription-ready, and built by the engineer behind a platform serving 10,000+ paying users.

Custom WordPress Plugin Development
Custom WordPress & WooCommerce plugins built to standard — by the developer behind a plugin with 5,000+ active installs and a SaaS with 10,000+ users.


