Skip to content
Advertisement

Having problems updating values in with array_walk_recursive

I’m working on code which needs to str_replace colons with spaces. Since i don’t know how deep my array will go i have to use array_walk_recursive function. The problem is that str_replace is not taken in to the account (read is not working). Please help me out guys.

This is my code

public function removeColonsFromStrings(array $inputs) {
    d($inputs); // some dump function
    array_walk_recursive($inputs, function (&$item, $key) {
        $inputs[$key] = str_replace(':',' ', $item);
    });
    dd($inputs); //dump and die function

    return $inputs;
}

and output is following

// first d() output
    array(7) {
      ["GivenName"]=>
      string(5) "Me"
      ["FamilyName"]=>
      string(7) "Me"
      ["DisplayName"]=>
      string(19) "[id:: 68]"
      ["CompanyName"]=>
      string(19) "[id:: 68]"
      ["FullyQualifiedName"]=>
      string(0) ""
      ["PrimaryPhone"]=>
      array(1) {
        ["FreeFormNumber"]=>
        string(0) ""
      }
      ["PrimaryEmailAddr"]=>
      array(1) {
        ["Address"]=>
        string(24) "my@email.com"
      }
    }

// Second dd() output    
    array(7) {
      ["GivenName"]=>
      string(5) "Me"
      ["FamilyName"]=>
      string(7) "Me"
      ["DisplayName"]=>
      string(19) "[id:: 68]"
      ["CompanyName"]=>
      string(19) "[id:: 68]"
      ["FullyQualifiedName"]=>
      string(0) ""
      ["PrimaryPhone"]=>
      array(1) {
        ["FreeFormNumber"]=>
        string(0) ""
      }
      ["PrimaryEmailAddr"]=>
      array(1) {
        ["Address"]=>
        string(24) "my@email.com"
      }
    }

So how to properly update values in my array? If you need any additional informations, please let me know and i will provide. Thank you!

Advertisement

Answer

While sending reference, you need to overwrite the old value.

array_walk_recursive($inputs, function (&$item, $key) {
  $item = str_replace(':',' ', $item);
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement