htmlspecialchars() for arrays / nested arrays

By Typo on 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:

array (
  1 => '<script />',
  2 => '<div bla="bla&bla2=morebla"',
  3 => 
  array (
    1 => '<script />',
    2 => '<div bla="bla&bla2=morebla"',
  ),
)

Would become:

array (
  1 => '&lt;script /&gt;',
  2 => '&lt;div bla=&quot;bla&amp;bla2=morebla&quot;',
  3 => 
  array (
    1 => '&lt;script /&gt;',
    2 => '&lt;div bla=&quot;bla&amp;bla2=morebla&quot;',
  ),
)
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:

<?php

function _clean(&$value) {
  $value = htmlspecialchars($value);
}

$a = array(
  1 => '<script />',
  2 => '<div bla="bla&bla2=morebla"',
  3 => array(
    1 => '<script />',
    2 => '<div bla="bla&bla2=morebla"',
  ),
);

array_walk_recursive($a, '_clean');
printf('<pre>%s</pre>', print_r($a, 1));

?>

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.