5

I try to pass a third parameter via reference to Phps array_walk_recursive

$field = 'foo';

array_walk_recursive($config, function($value, $key, &$field) {

    $field = 'bar';

}, $field);

echo $field // 'foo'

Why is $field still 'foo', though it has been passed to the function as reference?

1
  • 2
    double check docs. First, in your case $field is not array. Second, you need to pass first argument as reference for modification. Third: third argument is designed for passing additional data to callback function Commented Jul 15, 2014 at 6:57

3 Answers 3

13

According to the php documentation of anonymous functions inherited variables of a closure have to be defined in the functions header with the keyword use which leaves my example with:

function($value, $key) use (&$field) { ... }

Though the callback function inherits the parameters declared with use from its parent which means from the scope/function it has been declared (not executed) in.

Sign up to request clarification or add additional context in comments.

Comments

4
 <?php
        $field = array('foo');
        array_walk_recursive($field, function($value, $key) use(&$field) {
            $field = 'bar';
        });
        print_r($field);
        ?>

1 Comment

This provides a nice example, could have done with a short summary though, thanks
0

I had a similar problem, and I watched the changing of the values at the userdata parameter within the callback function. Here is what I discovered:

Assume this example-Code for testing:

$dataAr = array(
    "key1" => "...",
    "key2" => "...",
    "sub"  => array (
      "skey1" => "...",
      "skey2" => "...",
      "skey3" => "..."
    )
    "key3" => "...",
    "key4" => "...",
);

  $returnData = array("call_path");
  array_walk_recursive($dataAr, function ($value, $key, &$refField) {
    echo "call: ".$key . ":".implode("-",$refField["call_path"])."\n";
    $refField["call_path"][] = $key;
  },
  $returnData
);
echo "end :".implode("-",$returnData["call_path"])."\n";

Here are the results from my test:

call: key1 :.
call: key2 :.-key1
call: skey1:.-key1-key2
call: skey2:.-key1-key2-skey1
call: skey3:.-key1-key2-skey1-skey2

Until this point everything is like expected, but AFTER passing the sub-array:

call: key3:.-key1-key2
call: key4:.-key1-key2-key3
end : .

It seems to be, that the refference variable of the $userdata parameter in this function is always reseted to a previos value, when it comes from a sub array one level up.

So the refferece variable IF successfull change, but you cant see it after the function, because the starte value is restored in the last loop of each array.

I tested this in PHP 5.5.9

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.