php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #74653 foreach with reference and the ?: operator
Submitted: 2017-05-25 18:19 UTC Modified: 2017-05-25 18:40 UTC
From: david+php at porkrind dot org Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 7.1.5 OS: Ubuntu
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: david+php at porkrind dot org
New email:
PHP Version: OS:

 

 [2017-05-25 18:19 UTC] david+php at porkrind dot org
Description:
------------
In php 5.5, using the ?: operator in reference based foreach loops worked. In php 7.1 the reference doesn't affect the original array any more.

Test script:
---------------
<?php

$a=['hello' => [1,2,3]];

foreach ($a['hello'] ?: [] as &$x)
    $x++;

print_r($a);


Expected result:
----------------
In PHP 5.5 and PHP 5.6 the output is:

Array
(
    [hello] => Array
        (
            [0] => 2
            [1] => 3
            [2] => 4
        )

)


Actual result:
--------------
In PHP 7.1 the output is:

Array
(
    [hello] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-05-25 18:40 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2017-05-25 18:40 UTC] requinix@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.foreach

$a['hello'] ?: [] is an expression so the PHP 5 behavior was incorrect to begin with.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sun Jul 13 13:01:32 2025 UTC