Question

I have an haystack that's an associative array:

$array['header']['title'] = 'MyTitle';
$array['header']['subtitle'] = 'MySubtitle';
$array['body'] = 'MyBody';

I'd wish to replace every occurrence of 'My' with 'Your'.
I'm trying something like this:

$new_array = str_replace('My', 'Your', $array);

Sadly it works only on the first level (ie body key).
Is there anything wrong? Is there a workaround?

Was it helpful?

Solution

array_walk_recursive($array, 'replaceMy');

function replaceMy(&$item) {
    str_replace('My', 'Your', $item);
}

OTHER TIPS

Try this one: array_walk_recursive

If your associative array is unknown, you will have to use a recursive method to go through it and do your replace if the value is a string.

Otherwise, use more calls:

$new_array = str_replace('My', 'Your', $array);
$new_array = str_replace('My', 'Your', $array['header']);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top