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;
}
tags: intermediate / php / recursive / replace
8 comments
-
Posted: Jan 22, 2011
Hi, you have an error line 11.
The good line is :
$newArray[$key] = recursive_array_replace($find, $replace, $value);
512banque, SEO in France
-
Posted: Jan 31, 2011
For a multi-dimensional array (used within a class)….
————————————-
function recursive_arr_find_replace($arr, $find, $replace){
if(is_array($arr)){
foreach($arr as $key=>$val) {
if(is_array($arr[$key])){
$arr[$key] = $this->recursive_arr_find_replace($arr[$key], $find, $replace);
}else{
if($arr[$key] == $find) {
$arr[$key] = $replace;
}
}
}
}
return $arr;
}
function flip_arr_vals($arr, $val1, $val2){
$temp_val1 = “###”.$val1.”_”.$val2.”###”;
$arr = $this->recursive_arr_find_replace($arr, $val1, $temp_val1);
$temp_val2 = “###”.$val2.”_”.$val1.”###”;
$arr = $this->recursive_arr_find_replace($arr, $val2, $temp_val2);
$arr = $this->recursive_arr_find_replace($arr, $temp_val2, $val1);
$arr = $this->recursive_arr_find_replace($arr, $temp_val1, $val2);
return $arr;
} -
Posted: Feb 1, 2011
Sorry, part of that code was redundant. The second function uses the first for swapping two values within an array…
________________________function recursive_arr_find_replace($arr, $find, $replace){
if(is_array($arr)){
foreach($arr as $key=>$val) {
if(is_array($arr[$key])){
$arr[$key] = $this->recursive_arr_find_replace($arr[$key], $find, $replace);
}else{
if($arr[$key] == $find) {
$arr[$key] = $replace;
}
}
}
}
return $arr;
}
function flip_arr_vals($arr, $val1, $val2){
$temp_val1 = “###”.$val1.”_”.$val2.”###”;
$arr = $this->recursive_arr_find_replace($arr, $val1, $temp_val1);
$arr = $this->recursive_arr_find_replace($arr, $val2, $val1);
$arr = $this->recursive_arr_find_replace($arr, $temp_val1, $val2);
return $arr;
} -
Posted: Feb 19, 2011
hi, new to the site, thanks.
-
Posted: Apr 3, 2011
Ditto 512banque. Your recursive call is missing params.
-
Posted: Aug 29, 2011
Thanks for this bit of code: It’s helping me with some Webform work!
-
Posted: Nov 15, 2011
This worked perfectly, thank you so much!
-
Posted: Dec 21, 2011
Great script, cheers.


