PHP foreach Loop: How to Access Keys & Values in Arrays

php foreach loop

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.

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.

How PHP foreach Loop Works

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 foreach when you want to go through each value in an array or object. Other loops like for, while, or do...while do 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 for or while, 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. for and while need you to check array size or use count().
  • You can’t stop the loop early with a counter, but you can use the break statement.

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:

  • yield is 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.
  • foreach automatically 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?

It goes through each array element and runs code for it.

Can you get key and value in foreach?

Yes. Use foreach ($arr as $key => $value).

How do you change array values inside a foreach?

Use a reference: foreach ($arr as &$value).

Can you use foreach with objects?

Yes. It works with public properties.

Is foreach faster than for?

Yes, when you only need to read or update each item.

Does foreach work with nested arrays?

Yes. Use one foreach inside another.

What is the syntax for foreach?

Use foreach ($array as $value) or with keys: foreach ($array as $key => $value).

How do you build HTML with foreach?

Loop through array data and print tags inside the loop.

Similar Reads

PHP MySQL LIMIT Data: How to Optimize PHP Queries?

There are situations where you only need a specific number of rows returned. This is where the "LIMIT" clause in…

PHP array_keys: How to Extract Keys in Arrays with Examples

This guide shows how PHP array_keys finds all keys in an array and how you can filter them by a…

PHP Comment: How to Write Comments in PHP

let's now dive into PHP comments—these simple but super important integral parts of PHP coding. You can think of comments…

PHP File Inclusion: require, include, require_once, include_once

PHP offers four main functions to include files: require, require_once, include, and include_once. Each one gives you a similar purpose…

PHP Multidimensional Arrays: Data Manipulation

In web development, managing and manipulating data is one of the most common tasks. When it comes to storing complex…

PHP array_find: How to Locate Array Values with Examples

PHP array_find was released in PHP 8.4 to locate a value inside an array and returns the first match. Understand…

PHP array_any: How it Works with Arrays with Examples

PHP 8.4 released the array_any to test if at least one element matches a condition. Understand the array_any Function in…

PHP array_shift: Remove the First Array Element with Examples

The array_shift function in PHP takes the first element from an array and returns it. It also moves all other…

PHP strtolower Function: Convert Strings to Lowercase

Text does not always look the same. One word may appear in lowercase, another in uppercase. You want both to…

PHP filter_id Function: How to Retrieve PHP Filter IDs

Before PHP 5.2, there was no built-in filter extension in PHP. You had to manually handle and sanitize input. PHP…

Previous Article

PHP str_repeat: How it Works with Examples

Next Article

PHP abs Function: How to Get Absolute Values

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.