php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #79715 After the array element reference changes, use array_merge function produc
Submitted: 2020-06-19 07:52 UTC Modified: 2020-06-19 08:08 UTC
From: xyzzxf_2013 at 163 dot com Assigned:
Status: Not a bug Package: Unknown/Other Function
PHP Version: 7.3.4nts OS: centos 7/window 10
Private report: No CVE-ID: None
 [2020-06-19 07:52 UTC] xyzzxf_2013 at 163 dot com
Description:
------------
Reference value modification of element of array

Test script:
---------------
$a = ['23','25','26'];
foreach ($a as &$v) {
    $v = $v+1;
}
function get_check_code($data)
{
    foreach ($data as &$a) {
        $a = hexdec($a);
    }
    $sum = dechex(array_sum($data));
    return substr($sum, -2);
}
var_dump($a);
$b = get_check_code($a);
$c = array_merge($a,[$b]);
print_r($c);

Expected result:
----------------
var_dump($a) output array(3) { [0] => int(24) [1] => int(26) [2] => int(27) }

print_r($c) output Array ( [0] => 24 [1] => 26 [2] => 39 [3] => 71 )

Actual result:
--------------
The expected result of print_r($c) is Array ( [0] => 24 [1] => 26 [2] => 27 [3] => 71 )  or  Array ( [0] => 36 [1] => 38 [2] => 39 [3] => 71 )

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-06-19 07:57 UTC] xyzzxf_2013 at 163 dot com
-PHP Version: 7.2.31 +PHP Version: 7.3.4nts
 [2020-06-19 07:57 UTC] xyzzxf_2013 at 163 dot com
php version
 [2020-06-19 08:02 UTC] stas@php.net
-Type: Security +Type: Bug
 [2020-06-19 08:08 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 [2020-06-19 08:08 UTC] nikic@php.net
See https://www.php.net/manual/en/language.references.whatdo.php for how arrays and references interact. In particular, even if you pass an array by-value, it still retains any internal references. If your case, there is an active reference to the last array element. You can drop it by calling unset($v) after the foreach loop.

tl;dr Don't use references, just don't.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 14:01:32 2024 UTC