Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

`foreach` by reference with `&$row`

Use `&$row` to update array elements in place, then call `unset($row)` after the loop to detach the reference to the last visited element.

Version: PHP 8.3

Syntax

// The array syntax shown here requires no optional extensions in PHP 8.3.
foreach ($rows as &$row) {
    // Modify the current array element through $row.
}
unset($row);

// With a key:
foreach ($rows as $key => &$row) {
    // $key is the current key; $row is the element reference.
}
unset($row);

In PHP 8.3, foreach by reference &$row means writing foreach ($rows as &$row) so that $row becomes an alias for the current array element on each iteration. Updating $row['qty'] changes that field directly in $rows; assigning a new value to $row replaces the entire element. Here & binds by reference; it is not bitwise AND. In the form $key => &$row, $key receives the key by value.

If the loop ran at least once, $row still aliases the last visited element after the loop ends. Use unset($row) immediately afterward: it breaks the binding without deleting the element or undoing your changes. Otherwise, a later assignment to $row, even in a plain foreach ($rows as $row) without &, can silently overwrite that element.

To read ordinary array rows, use foreach ($rows as $row) and make sure $row is not already a reference. With that by-value binding, assigning to $row does not replace the element in $rows. The array syntax shown here requires no additional extensions.

Examples

<?php
$rows = [
    ['item' => 'A', 'qty' => 2],
    ['item' => 'B', 'qty' => 5],
];

foreach ($rows as &$row) {
    $row['qty'] += 1;
}
unset($row);

foreach ($rows as $row) {
    echo $row['item'], ': ', $row['qty'], "\n";
}

Result

A: 3
B: 6

The first loop increases both quantities, and the second reads the updated rows. Without `unset($row)`, the second loop would overwrite the last row and print `A: 3` twice.

Related lessons

  • PHP · Lesson 19 · Advanced · Version: 2

Sources