Jump to content

just built this function, how can I make it better? (multidimensional)


raccer

Recommended Posts

/**
 * preforms a str_replace on every key in passed array (1-Dimensional only)
 *
 * @param $array the array to be processed
 * @param $pattern the string to be replaced/removed
 * @param $replace(optional) leave empty to remove $pattern,
 * 		   or pass a string to replace with.
 *
 * @return the new array
 */
function keyReplace($array, $pattern, $replace = "") {
	$newArray = array();
	foreach ($array as $key => $value) {
		$newKey = str_replace($pattern, $replace, $key);
		$newArray[$newKey] = $value;
	}
	return $newArray;
}

 

I'm a programming noob, just finishing my first php class.... so go easy on me

 

Whats the simplest way to make this function multidimensional array capable? I.E. every key on nth level will be processed.

 

Thanks for the input!

Make it more re-usable:

 

function keyReplace($key, $pattern, $replace) {
  return str_replace($pattern, $replace, $key);
}

function replaceKeys($array, $pattern, $replace) {
  foreach (array_keys($array) as $key) {
    keyReplace($key, $pattern, $replace);
  }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.