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 => '<script />',
2 => '<div bla="bla&bla2=morebla"',
3 =>
array (
1 => '<script />',
2 => '<div bla="bla&bla2=morebla"',
),
)
function htmlspecial_array(&$variable) {
foreach ($variable as &$value) {
if (!is_array($value)) { $value = htmlspecialchars($value); }
else { htmlspecial_array($value); }
}
}
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 :)