Quick snip: Recursive find and replace

Q

The problem:
We have a multidimensional array and have to find and replace some values. It would be the best if the result is the same array with values changed.

The solution:
We need to write a simple function which will be called recursively to generate a resulting array.

Here it is:

function rec_array_replace($find, $replace, $array){ 
	
	if (!is_array($array)) { 
		return str_replace($find, $replace, $array);
	}
	
	$newArray = array();
	
	foreach ($array as $key => $value) {
		$newArray[$key] = rec_array_replace($value);
	}
	
	return $newArray;
}

It is quite straightforward but I will explain anyway. Function first checks if $array is actually an array and if it isn’t, it returns regular str_replace. If it is an array, we are creating empty array $newArray.

We advance through the given array by key and value and call recursively the same function. This time $array is not an array and the function returns regular str_replace, which is our value.

That’s it.

About the author

Zvonko Biškup

A passionate web developer with more than 13 years experience in PHP and other web related technology. My main interest is WordPress and new PHP frameworks.
Owner of Influendo Programming.
Enjoys exploring new stuff and possibilities, using new technologies and just having fun developing awesome stuff.

By Zvonko Biškup

Tags