foreach by Reference

as &$v writes straight into the array — PHP foreach by reference against traversal write-back in 10 languages.

C C23

C23
#include <stdio.h>

/* C has no foreach: a walking pointer is the classic in-place traversal */
int main(void) {
    int nums[] = {1, 2, 3};
    for (int *p = nums; p < nums + 3; p++) {
        *p *= 10;
    }
    printf("%d,%d,%d\n", nums[0], nums[1], nums[2]);
    return 0;
}
Output
10,20,30

C++ C++26

C++26
#include <cstdio>
#include <vector>

// the range-for can bind a reference, so in-place mutation is direct
int main() {
    std::vector<int> nums{1, 2, 3};
    for (int &v : nums) {
        v *= 10;
    }
    std::printf("%d,%d,%d\n", nums[0], nums[1], nums[2]);
}
Output
10,20,30

C# v11.0.100

v11.0.100
var nums = new List<int> { 1, 2, 3 };
// foreach's iteration variable is read-only; the for-index form writes back
for (var i = 0; i < nums.Count; i++) {
    nums[i] *= 10;
}
Console.WriteLine(string.Join(",", nums));
Output
10,20,30

Go v1.27.4

v1.27.4
package main

import "fmt"

// range yields a copy of the element; the index form is how you write back
func main() {
	nums := []int{1, 2, 3}
	for i := range nums {
		nums[i] *= 10
	}
	fmt.Println(nums)
}
Output
[10 20 30]

Java v27.0.1

v27.0.1
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        // the for-each variable is a copy; the index form writes back
        for (int i = 0; i < nums.length; i++) {
            nums[i] *= 10;
        }
        System.out.println(Arrays.toString(nums));
    }
}
Output
[10, 20, 30]

JavaScript v26.13.1

v26.13.1
const nums = [1, 2, 3];
// for...of yields copies of the primitive elements; write back by index
for (let i = 0; i < nums.length; i++) nums[i] *= 10;
console.log(nums.join(","));
Output
10,20,30

PHP v8.6.0

v8.6.0
$a = [1, 2, 3];
$b = $a;      // COW: physical storage still shared
$b[0] = 99;   // write: the two arrays split here
echo implode(",", $a), "\n"; // a untouched by the copy

// foreach by reference: as &$v walks the ORIGINAL array and each write
// lands in place — this also breaks COW the moment the loop starts
foreach ($a as &$v) {
    $v++; // increments live in $a itself
}
unset($v); // housekeeping: drop the leftover reference to $a[2]

echo implode(",", $a), "\n";

// the classic in-place map
$nums = [1, 2, 3];
foreach ($nums as &$n) {
    $n *= 10;
}
unset($n);
echo implode(",", $nums), "\n";
Output
1,2,3
2,3,4
10,20,30

Python v3.15.2

v3.15.2
nums = [1, 2, 3]
for i in range(len(nums)):  # ints are immutable: write back by index
    nums[i] *= 10
print(nums)
Output
[10, 20, 30]

Rust v1.99.1

v1.99.1
// iter_mut() walks the elements through a mutable borrow, so writes land
// in the Vec directly — the truest analogue of foreach (as &$v)
fn main() {
    let mut nums = vec![1, 2, 3];
    for v in nums.iter_mut() {
        *v *= 10;
    }
    println!("{:?}", nums);
}
Output
[10, 20, 30]

TypeScript v26.13.1

v26.13.1
const nums: number[] = [1, 2, 3];
// for...of yields copies of the primitive elements; write back by index
for (let i = 0; i < nums.length; i++) nums[i] *= 10;
console.log(nums.join(","));
Output
10,20,30

Language differences

C: pointer traversal (example): an int *p walks the array and *p rewrites in place — C programmers' foreach for decades; out-of-bounds walking is unprotected.

C++: range-for with a reference binding (example): for (int &v : nums) mirrors PHP's as &$v — the reference lands directly on the element; a value binding for (int v : nums) copies (writes go nowhere); for_each plus back_inserter is the functional route.

C#: the foreach iteration variable is read-only (example): enforced by the compiler — assigning to it is a compile error; write back via the for index or List<T>.ForEach; no by-reference traversal syntax.

Go: range copies the value (example): v in for _, v := range is a copy of the element and assignment goes nowhere; writing back requires the index form nums[i]; for i := range nums yielding only the index is the most idiomatic shape.

Java: the for-each variable is a copy (example): primitive arrays cannot be written through it; object arrays can mutate element internals but not replace the element; write back via indexes or streams; no by-reference traversal.

JavaScript: for...of has no references (example): primitive elements come out as copies and writes go nowhere; the idioms are index loops, map/filter producing new arrays, or Object.entries destructuring; no by-reference traversal syntax.

PHP: as &$v (example): the loop variable automatically becomes a reference to the current element, so writes modify the original array in place (asserted by the second and third blocks); starting a by-reference traversal breaks COW — the original array stops sharing with any copies; unset($v) after the loop is mandatory housekeeping (a leftover reference makes later same-name assignments silently rewrite the last element); for and array_map are the alternatives.

Python: the index school (example): v in for v in nums is an object reference, but assigning to an immutable int just rebinds the name — nothing writes back; the idioms are enumerate indexes, list comprehensions, or mutating mutable element internals directly; no by-reference traversal syntax.

Rust: iter_mut() (example): mutable-borrow traversal is the semantic counterpart of PHP's as &$v — writes land directly in the Vec; the borrow checker forbids borrowing the Vec again while iterating (no iterator-invalidation bugs); into_iter() consumes and iter() is read-only.

TypeScript: at the language level the same as JS (example): for...of copies primitive elements and write-back goes by index; the type system can express a read-only traversal (for (const v of nums as readonly number[])) but the write-back semantics are unchanged; idioms are exactly JS's.