PHP foreach loop came to help work with array data in a simple way. Arrays and objects grew more common in real projects. Other loop types had too many steps for reading or updating every array element. Developers needed faster ways to iterate over array items.
Table of Content
- Understand the PHP foreach Loop
- How foreach Loop Works in PHP
- Loop Through Associative Arrays with foreach Loop in PHP
- The Difference Between the foreach Loop and Other Loops in PHP
- Access Keys and Values in the foreach Loop in PHP
- Use foreach Loop with Objects
- Use foreach with Nested Arrays in PHP
foreachwith Generatorsforeachwithlist()/ Destructuring- PHP foreach Loop Examples
- Wrapping Up
- FAQs
Understand the PHP foreach Loop
The foreach loop goes through each item in arrays and objects. It handles one array element at a time. It works well when you do not need to count indexes. You just want the key value pair and you want to act on each one.
Here is the syntax:
foreach ($array as $value) {
// code runs here
}You can also include keys:
foreach ($array as $key => $value) {
// use both key and value
}Here is a quick example:
$tuts = ["PHP", "Basics", "Advanced"];
foreach ($tuts as $tut) {
echo $tut . "\n";
}This is an indexed array. The loop goes through each string and prints it. Here is the output:
PHP
Basics
Advanced
This code creates an array $tuts with three strings, then loops through each item and prints it with a newline. It outputs each string name on its own line.
How foreach Loop Works in PHP
The foreach loop in PHP goes through each item in an array one by one. It runs some code for each item based on a few simple rules.

Here is what happens. First, foreach grabs the first item in the array. It takes that value and puts it into a variable.
You choose the name of that variable when you write the loop. That variable holds the current value as the loop moves through the array.
Then it runs the code inside the curly braces { }. That code can do anything—like show the value or change it.
After that, it moves to the next item and repeats the same steps. It keeps doing this until it reaches the last item in the array.
There is one thing to remember. The variable inside the loop only holds a copy of the array value. If you change it, the original array stays the same.
Loop Through Associative Arrays with foreach Loop in PHP
Associative arrays store data with named keys. The foreach reads each key value pair and makes it easy to use both.
For example:
$user = ["name" => "Jane", "age" => 30];
foreach ($user as $key => $value) {
echo "$key: $value\n";
}This prints key value echo key and value for each item. Here is the output:
name: Jane
age: 30
For another example:
$prices = ["apple" => 5, "banana" => 3];
foreach ($prices as $item => $cost) {
echo "$item costs $cost\n";
}This code loops through the $prices array and prints each item with its cost. Output:
apple costs 5
banana costs 3
The Difference Between the foreach Loop and Other Loops in PHP
The foreach loop reads all items without tracking counters. Other loops like for or while need manual setup. The foreach fits arrays and objects.
Here is a point list showing the difference between the foreach loop and other loops in PHP:
- You can use
foreachwhen you want to go through each value in an array or object. Other loops likefor,while, ordo...whiledo not need arrays. They use conditions or counters. - You do not set a start or end point. PHP picks each value from the array in order. With
fororwhile, you control the index with a counter. - You can get the key and the value in each loop step. Other loops need extra steps to access the key or use array functions.
- It only goes forward through the array. You cannot loop backward without changing the array or using another loop.
- If you change the loop variable, it does not affect the original array unless you use a reference (
&). Other loops can update the array directly if you access it by index. - PHP handles that inside the loop.
forandwhileneed you to check array size or usecount(). - You can’t stop the loop early with a counter, but you can use the
breakstatement.
Access Keys and Values in the foreach Loop in PHP
Iterate with keys and values in the foreach loop:
foreach ($data as $key => $value) {
echo "$key => $value\n";
}It prints each key-value pair from the $data array in the format:
key => value
It runs once for each element in the array.
Update the array elements within the foreach loop:
foreach ($data as &$value) {
$value += 1;
}This loop increases each value in the $data array by 1. The & makes $value a reference, so changes affect the original array.
Modify array values inside a foreach loop:
Use & to change values, for example:
foreach ($list as &$item) {
$item = strtoupper($item);
}This loop converts each string in the $list array to uppercase using strtoupper(). The & means it updates the original array directly.
Use foreach Loop with Objects
You can use foreach on class properties if they are public. Use inside the class or with a method.
class Item {
public $name = "box";
public $count = 10;
public function __construct() {
// setup
}
}
$item = new Item();
foreach ($item as $key => $value) {
echo "$key: $value\n";
}This code creates an Item object with two public properties: $name and $count. The foreach loop iterates over the object’s public properties and prints:
name: box
count: 10
Only public properties are accessible in object iteration.
Use foreach with Nested Arrays in PHP
Nested arrays hold more arrays inside them. Use foreach inside another foreach:
$nested = [["a", "b"], ["c", "d"]];
foreach ($nested as $arr) {
foreach ($arr as $value) {
echo $value . "\n";
}
}This code loops through a nested array and prints each value on a new line. Output:
a
b
c
d
It uses two foreach loops to access inner array elements.
foreach with Generators
You can use foreach to loop over objects that implement the Iterator interface or use yield (Generators).
For example:
function numbers() {
for ($i = 1; $i <= 3; $i++) {
yield $i;
}
}
foreach (numbers() as $number) {
echo $number . "\n";
}Output:
1
2
3
Here is how it works:
yieldis used to create a generator, which provides values one at a time without storing them all in memory.- Each call to
yield $i;returns the next value, and pauses the function until the next iteration. foreachautomatically calls the generator and handles the iteration.
foreach with list() / Destructuring
PHP supports unpacking arrays inside foreach using list().
$pairs = [[1, 2], [3, 4]];
foreach ($pairs as list($a, $b)) {
echo "$a, $b\n";
}Output:
1, 2
3, 4
PHP 7.1+ supports short array syntax:
foreach ($pairs as [$a, $b]) {
echo "$a:$b\n";
}Output:
1:2
3:4
PHP foreach Loop Examples
Print all values in an array with foreach:
foreach ($items as $item) {
echo $item;
}This loop prints each element in the $items array without spaces or line breaks. It runs once for every item in the array.
Build an HTML table from an array with foreach:
echo "<table>";
foreach ($data as $row) {
echo "<tr><td>$row</td></tr>";
}
echo "</table>";This code creates an HTML table where each value in the $data array becomes a row. Output example:
<table>
<tr><td>Value1</td></tr>
<tr><td>Value2</td></tr>
...
</table>
Each array item is wrapped in a <tr><td> row.
Loop through $_POST or $_GET data with foreach:
foreach ($_POST as $key => $value) {
echo "$key = $value\n";
}This loop prints each key-value pair from the $_POST form data. Example output:
username = john
email = [email protected]
It helps debug or process submitted form inputs.
Use foreach to format JSON data in PHP:
$json = '["a", "b"]';
$data = json_decode($json);
foreach ($data as $item) {
echo $item;
}This code converts the JSON string into a PHP array, then loops through it to print each item. Output:
ab
It prints each element without spaces or line breaks.
Create an HTML list from an array with foreach:
echo "<ul>";
foreach ($list as $entry) {
echo "<li>$entry</li>";
}
echo "</ul>";This code creates an HTML unordered list. It wraps each $list item inside <li> tags, producing:
<ul>
<li>Item1</li>
<li>Item2</li>
...
</ul>
Each array element becomes a list item.
Loop through multidimensional arrays with foreach:
foreach ($records as $row) {
foreach ($row as $field) {
echo $field;
}
}This code loops through a 2D array $records and prints all fields one after another without spaces or breaks. It uses nested foreach loops to access each inner value.
Use foreach with reference to modify original array:
foreach ($values as &$v) {
$v *= 2;
}This loop doubles each value in the $values array. The & makes $v a reference, so changes update the original array directly.
Group array data by key with the foreach loop:
$grouped = [];
foreach ($people as $p) {
$grouped[$p['role']][] = $p;
}This code groups $people by their 'role'. For each person $p, it adds them to the $grouped array under the key matching their role.
Wrapping Up
In this article you learned how to use the foreach loop with arrays and objects. You also saw how to update array elements and how to read keys and values.
Here is a quick recap:
- Use foreach to iterate over array data
- foreach array as key lets you access both parts
- Use reference to update values
- foreach loop works better than for and while for most arrays
- You can loop in PHP through objects, nested arrays, and $_POST data
FAQs
What is a foreach loop in PHP?
Can you get key and value in foreach?
How do you change array values inside a foreach?
Can you use foreach with objects?
Is foreach faster than for?
Does foreach work with nested arrays?
What is the syntax for foreach?
How do you build HTML with foreach?
Similar Reads
There are situations where you only need a specific number of rows returned. This is where the "LIMIT" clause in…
This guide shows how PHP array_keys finds all keys in an array and how you can filter them by a…
let's now dive into PHP comments—these simple but super important integral parts of PHP coding. You can think of comments…
PHP offers four main functions to include files: require, require_once, include, and include_once. Each one gives you a similar purpose…
In web development, managing and manipulating data is one of the most common tasks. When it comes to storing complex…
PHP array_find was released in PHP 8.4 to locate a value inside an array and returns the first match. Understand…
PHP 8.4 released the array_any to test if at least one element matches a condition. Understand the array_any Function in…
The array_shift function in PHP takes the first element from an array and returns it. It also moves all other…
Text does not always look the same. One word may appear in lowercase, another in uppercase. You want both to…
Before PHP 5.2, there was no built-in filter extension in PHP. You had to manually handle and sanitize input. PHP…