Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Iterating over an array by reference with `foreach`

Put `&` before the value variable to edit array elements in place. Call `unset($p)` after the loop so later assignments cannot change the last visited element through that variable.

Version: PHP 8.3

Syntax

foreach ($projects as &$p) {
    // Modify the current array element through $p.
}
unset($p);

In PHP 8.3, foreach by-reference iteration makes the value variable an alias for the current array element. This syntax is built into PHP and requires no optional extension. In foreach ($projects as &$p), assigning to $p replaces the whole element, while assigning to $p['status'] updates that field in the original $projects array. If you also need the key, use foreach ($projects as $key => &$p): only the value is bound by reference.

If the loop visited any elements, $p remains an alias for the last one visited, even if the loop ended with break. Call unset($p) immediately after the loop to remove the binding without deleting the array element. Assigning $p = null is not a substitute: it writes null into that element.

For reading, use foreach ($projects as $p) without &. For the array of records in this example, assigning to an unbound $p or to $p['status'] in a by-value loop does not update $projects. But if you skip unset($p), a later by-value loop that reuses $p can overwrite the last visited element as it assigns each value.

Examples

<?php
$projects = [
    ['name' => 'Atlas', 'status' => 'draft'],
    ['name' => 'Beacon', 'status' => 'review'],
];

foreach ($projects as &$p) {
    if ($p['status'] === 'draft') {
        $p['status'] = 'ready';
    }
}
unset($p);

foreach ($projects as $p) {
    echo $p['name'], ': ', $p['status'], "\n";
}

Result

Atlas: ready
Beacon: review

The first loop changes Atlas from `draft` to `ready`. After `unset($p)`, the second loop safely reuses `$p` to print both projects; Beacon stays at `review`.

Related lessons

  • PHP · Lesson 14 · Intermediate · Version: 3
  • PHP · Lesson 22 · Intermediate · Version: 3

Sources