php / php/php-src

Dereferencing an array in foreach unwraps the reference

Open
#11,665 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Status: Needs Triage
Dominant language
C
Stars
40.4k
Forks
8.1k
Avg merge
2d 13h
Merged PRs (30d)
96

Description

Description

The following code (https://3v4l.org/8QBeN):

<?php

$a = [1]; 
foreach ((isset($a["key"]) ? [&$a["key"]] : [&$a])[0] as &$v) {
    var_dump($a);
    $v++;
}
var_dump($a);

Resulted in this output:

array(1) {
  [0]=>
  int(1)
}
array(1) {
  [0]=>
  int(1)
}

But I expected this output instead:

array(1) {
  [0]=>
  &int(1)
}
array(1) {
  [0]=>
  &int(2)
}

In PHP 7.2 and before, the output was as expected. Today it's required to use an explicit variable to preserve the reference.

PHP Version

PHP 7.3.0 - master

Operating System

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the PHP reproducer linked in the issue and compare its behavior between PHP 7.2 and the reported PHP 7.3 version. Investigate how the foreach reference is handled when iterating over the conditional array expression. Done means the reference is preserved and the output matches the expected result, without requiring an explicit temporary variable.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.