0

How do I search and replace an entire multi-level array in PHP? As in something like:

$a = array(
  'level1' => array(
    'level2' => array(
      'level3' => 'foo'
    )
    'level2b' => array(
      'level3b' => 'foo'
    )
);

So, replace 'foo' with 'bar'.

BACKGROUND: I'm having to do this on a serialized array from a WordPress blog since we're moving this blog to another directory name.

1
  • why not create a function for that? I see you can do it... Commented Feb 6, 2013 at 16:17

1 Answer 1

5

Very simple with array_walk_recursive

array_walk_recursive($a, function (&$val) {
  $val = str_replace('foo', 'bar', $val);
});

print_r($a);

Just make sure to use a reference (&$val).

demo: http://codepad.viper-7.com/7L33Fg

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

1 Comment

I just never had the need to do this before until now, and wasn't aware of the array_walk_recursive() function before. Awesome that you found that, and awesome that you knew of the &$val thing.

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.