php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #67633 A foreach on an array returned from a function not doing copy-on-write
Submitted: 2014-07-16 15:11 UTC Modified: 2014-07-16 16:35 UTC
Votes:2
Avg. Score:5.0 ± 0.0
Reproduced:2 of 2 (100.0%)
Same Version:2 (100.0%)
Same OS:2 (100.0%)
From: tim at siliconengine dot com Assigned: nikic (profile)
Status: Closed Package: Arrays related
PHP Version: 5.5.14 OS: CentOS 6.5
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: tim at siliconengine dot com
New email:
PHP Version: OS:

 

 [2014-07-16 15:11 UTC] tim at siliconengine dot com
Description:
------------
When passing an array by value to a function, which immediately returns that array, and then using that return value in a foreach with a reference, it allows modifying the original array as if it was passed by reference.

These variants work properly:

............. Variant 1
[same main body]

function z($t)
{
// Force copy-on-write
    $t[0] .= 'x';
    return $t;
}
.............


............. Variant 2
    $a = [ 'a', 'b', 'c' ];
    $b = z($a);
// Assigning to variable causes proper copy-on-write behavior
    foreach($b as &$x) {
        $x .= 'q';
    }
    print_r($a);

[same z function]
.............

Test script:
---------------
<?php
    $a = [ 'a', 'b', 'c' ];
    foreach(z($a) as &$x) {
        $x .= 'q';
    }
    print_r($a);

function z($t)
{
    return $t;
}


Expected result:
----------------
Array
(
    [0] => a
    [1] => b
    [2] => c
)


Actual result:
--------------
Array
(
    [0] => aq
    [1] => bq
    [2] => cq
)


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-07-16 16:35 UTC] nikic@php.net
-Assigned To: +Assigned To: nikic
 [2014-09-20 19:59 UTC] nikic@php.net
Automatic comment on behalf of nikic
Revision: http://git.php.net/?p=php-src.git;a=commit;h=5e977e69e144ca92868ae73cd3563eb473b75937
Log: Fixed bug #67633
 [2014-09-20 19:59 UTC] nikic@php.net
-Status: Assigned +Status: Closed
 [2014-09-20 20:00 UTC] nikic@php.net
Automatic comment on behalf of nikic
Revision: http://git.php.net/?p=php-src.git;a=commit;h=5e977e69e144ca92868ae73cd3563eb473b75937
Log: Fixed bug #67633
 [2014-09-20 20:00 UTC] nikic@php.net
Automatic comment on behalf of nikic
Revision: http://git.php.net/?p=php-src.git;a=commit;h=5e977e69e144ca92868ae73cd3563eb473b75937
Log: Fixed bug #67633
 [2014-09-22 08:28 UTC] ab@php.net
Automatic comment on behalf of nikic
Revision: http://git.php.net/?p=php-src.git;a=commit;h=5e977e69e144ca92868ae73cd3563eb473b75937
Log: Fixed bug #67633
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 14:01:29 2024 UTC