htmlspecialchars() for arrays / nested arrays

By Typo
Platform:  PHP
Published  May 15, 2011
Updated  May 15, 2011
This is a very simple function that will run htmlspecialchars() on every value in an array. The function is recursive (calls itself) so even if it holds nested arrays it will still work.

For example:

Code

 

Would become:

Code

 
function htmlspecial_array(&$variable) {
foreach ($variable as &$value) {
if (!is_array($value)) { $value = htmlspecialchars($value); }
else { htmlspecial_array($value); }
}
}

Comments

Sign in to comment.
sean   -  May 03, 2012
Great example @Typo !
You could also look into using array_walk_recursive. Consider the following:

Code

 

This route makes things a bit easier if you need add more data cleaning methods :)
 Respond  
Hawkee   -  May 15, 2011
Great to see you posting again Typo. Interesting use of pointers, not too common to see that in PHP.
 Respond  
Typo   -  May 15, 2011
All comments are welcome.
 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.