Skip to content

A reference taken to a by-ref foreach variable ($out[$k] = &$v, [&$v]) points at the loop's copy, not the element. #439

Closed

Description

@blacktrs

Summary

A reference taken to a by-ref foreach variable ($out[$k] = &$v, [&$v]) points at the loop's copy, not the element.

Repro

<?php
final class Stmt {
    /** @var array<int, mixed> */
    private array $bound = [];
    public function keep(mixed &...$vars): bool { $this->bound = []; foreach ($vars as $i => &$v) { $this->bound[$i] = &$v; } return true; }
    public function fill(int $n): void { foreach ($this->bound as $i => &$v) { $v = $n === 1 ? $i : ($n === 2 ? "s$i" : null); } }
}
$s = new Stmt();
$s->keep($a, $b);
$s->fill(3); var_dump($a, $b);
$s->fill(1); var_dump($a, $b);
$s->fill(2); var_dump($a, $b);
/** @param array<int, mixed> $vars @return array<int, mixed> */
function keepl(array $vars): array { $out = []; foreach ($vars as $i => &$v) { $out[$i] = &$v; } $vars[0] = 'w'; var_dump($out[0]); return $out; }
keepl([1, 2]);
function lit(): void { $arr = [1, 2]; foreach ($arr as &$v) { $l = [&$v]; $l[0] = 'y'; } unset($v); var_dump($arr[0], $arr[1]); }
lit();

Expected (php)

NULL
NULL
int(0)
int(1)
string(2) "s0"
string(2) "s1"
string(1) "w"
string(1) "y"
string(1) "y"

Actual (manticore 1b3f58ac, Darwin arm64)

float(2.1358401783E-314)
float(2.1358401783E-314)
float(2.1358401783E-314)
float(2.1358401783E-314)
float(2.1358401783E-314)
float(2.1358401783E-314)
int(2)
int(4322988840)
int(4322988840)

Tracking

Known-bug repro: tests/aot/repro/wrong/byref_variadic_foreach_keep.php — bash tests/aot/xfail.sh -k byref_variadic_foreach_keep reports XFAIL while this is open and XPASS once it is fixed; then move the repro into tests/aot/cases/ and close this issue.

Activity

  1. added
    bug
    wrong-answer
    on Oct 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugwrong-answer

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions