categories: development / tutorials /
If you've ever worked with the str_replace() function in PHP you may or may not have come across the issue with it not recursively looping through arrays.
I recently came across this issue when having to deal with a multi-dimensional array that I needed to have scrubbed for certain values. Here's the quick code snippet I wrote to take care of this little task.
// Recursive String Replace - recursive_array_replace(mixed, mixed, array);
function recursive_array_replace($find, $replace, $array){
if (!is_array($array)) {
return str_replace($find, $replace, $array);
}
$newArray = array();
foreach ($array as $key => $value) {
$newArray[$key] = recursive_array_replace($value);
}
return $newArray;
}