php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #71969 str_replace returns an incorrect resulting array after a foreach by reference
Submitted: 2016-04-05 17:22 UTC Modified: -
From: vad at bitrix dot ru Assigned:
Status: Closed Package: Arrays related
PHP Version: 7.0.5 OS: CentOS
Private report: No CVE-ID: None
 [2016-04-05 17:22 UTC] vad at bitrix dot ru
Description:
------------
After foreach by reference, with the array value changing, the array is passed to the str_replace() as a subject. It's expected to get the array back unchanged, but it's broken with a "Notice: Array to string conversion".

This is only PHP 7 related, earlier versions are OK.

https://3v4l.org/iOlfo

Test script:
---------------
$a = array(
	array("one" => array("a"=>"0000", "b"=>"1111")),
);

//foreach by reference, changing the array value
foreach($a as &$record)
{
	$record["one"]["a"] = "2222";
}

var_dump($a);

var_dump(str_replace("2", "3", $a));

Expected result:
----------------
array(1) {
  [0]=>
  &array(1) {
    ["one"]=>
    array(2) {
      ["a"]=>
      string(4) "2222"
      ["b"]=>
      string(4) "1111"
    }
  }
}
array(1) {
  [0]=>
  array(1) {
    ["one"]=>
    array(2) {
      ["a"]=>
      string(4) "2222"
      ["b"]=>
      string(4) "1111"
    }
  }
}

Actual result:
--------------
array(1) {
  [0]=>
  &array(1) {
    ["one"]=>
    array(2) {
      ["a"]=>
      string(4) "2222"
      ["b"]=>
      string(4) "1111"
    }
  }
}

Notice: Array to string conversion in /in/iOlfo on line 14
array(1) {
  [0]=>
  string(5) "Array"
}

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-04-06 02:21 UTC] laruence@php.net
Automatic comment on behalf of laruence@gmail.com
Revision: http://git.php.net/?p=php-src.git;a=commit;h=e95782ed5e26c041d62b847dc772f86fe6b01516
Log: Fixed bug #71969 (str_replace returns an incorrect resulting array after a foreach by reference)
 [2016-04-06 02:21 UTC] laruence@php.net
-Status: Open +Status: Closed
 [2016-07-20 11:32 UTC] davey@php.net
Automatic comment on behalf of laruence@gmail.com
Revision: http://git.php.net/?p=php-src.git;a=commit;h=e95782ed5e26c041d62b847dc772f86fe6b01516
Log: Fixed bug #71969 (str_replace returns an incorrect resulting array after a foreach by reference)
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Oct 15 10:01:27 2024 UTC