Jump to content

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


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);
  }
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.