Stripslashes all values in an array with PHP.

Here is a very simple function to run stripslashes on an array and all of its child arrays. The function below is for PHP 5 and takes a single argument which should consist of an array. It loops through all elements of the array, and if an element is an array, it calls itself on the child array to an infinite depth. Of course this can cause memory problems if your arrays are dynamically created with an excessively large depth, but for most uses, it will function perfectly.

The Code

function unstrip_array($array){
	foreach($array as &$val){
		if(is_array($val)){
			$val = unstrip_array($val);
		}else{
			$val = stripslashes($val);
		}
	}
return $array;
}

Why would I need to unstrip an entire array?

It’s useful for WordPress Plugin developers or anyone whose scripts might be run on a server with magic quotes enabled. It is also excellent to strip any slashes from $_POST inputs that might confuse your attempts to escape the strings later. Running an array of post data through this will make it easier to ensure that you don’t have hacking attempts.

3 Responses to Stripslashes all values in an array with PHP.

  1. R says:

    thanks a lot, I’m sure it saved me a lot of time!

    • brando says:

      Thanks for this function…yet aren’t you missing something here? You are setting the $val to the newly stripped string, but you never re-create the array. Returning the $array will give you the same thing you started with.

Leave a Reply

Standard Rules Apply: Use <code> tags for code snippets. Keep it relevant. Other than that, be your awesome self.

*(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Social Social
Hide