PHP: how to perform htmlspecialchar() on an array-of-arrays?

function filter(&$value) {
  $value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
array_walk_recursive($result_set, "filter");
print_r($result_set);

You can use array_map() to run that method on each entry.

$cleaned = array_map("htmlspecialchars", $myArray);

If you need to pass arguments to htmlspecialchars(), you can substitute it for your own custom function:

function myFunc($a) {
  return htmlspecialchars($a, ENT_QUOES);
}

$cleaned = array_map("myFunc", $myArray);

Considering the fact that you're dealing with an array of arrays, and not an array of strings, you would need to cycle through the outer-array to get to your strings:

$cleaned = array();
foreach ($result_set as $rs) {
  foreach ($rs as $r) {
    $cleaned[] = array_map("htmlspecialchars", $r);
  }
}

Or, you could use array_walk_recursive():

array_walk_recursive($myArray, "htmlspecialchars");

Note that this method changes the $myArray object by reference, so there's no need to assign the output to a new variable.


You may wish to use array_map as Jonathon Sampson suggested, another alternative is array_walk

The difference is that array_map returns a copy of the array with the function applied to each element, while array_walk operates directly on the array you supply.