php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #34982 array_walk_recursive() modifies elements outside function scope
Submitted: 2005-10-25 21:24 UTC Modified: 2005-10-28 11:58 UTC
From: curt@php.net Assigned: dmitry
Status: Closed Package: Arrays related
PHP Version: 5CVS-2005-10-25 (CVS) OS: *
Private report: No CVE-ID:
 [2005-10-25 21:24 UTC] curt@php.net
Description:
------------
array_walk_recursive() modifies element values deeper than the first level on vars outside the scope of the function call.



Reproduce code:
---------------
<?php

$ar = array(
    'element 1',
    array('element2 => subelement1')
    );

func($ar);
var_dump($ar);

function func($a) {
  array_walk_recursive($a, 'apply');
}

function apply(&$input, $key) {
  $input = 'changed';
}


Expected result:
----------------
array(2) {
  [0]=>
  string(9) "element 1"
  [1]=>
  array(1) {
    [0]=>
    string(23) "element2 => subelement1"
  }
}


Actual result:
--------------
array(2) {
  [0]=>
  string(9) "element 1"
  [1]=>
  array(1) {
    [0]=>
    string(7) "changed"
  }
}


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-10-25 21:57 UTC] tony2001@php.net
I'd say the bug is that it *doesn't* modify the first level elements, because it's expected when you use &$arg instead of $arg.
 [2005-10-26 04:52 UTC] curt@php.net
Mabey I didn't make the code clear but if you var_dump($a) right after array_walk_recursive() all values have the value of 'changed'. The problem is back outside of the function that called array_walk_recursive(), the $ar variable should still retain the original array values.
 [2005-10-28 11:58 UTC] dmitry@php.net
Fixed in CVS HEAD, PHP_5_1 and PHP_5_0.
 
PHP Copyright © 2001-2014 The PHP Group
All rights reserved.
Last updated: Sun Apr 20 15:01:54 2014 UTC