2

I use array_walk_recursive to apply htmlspecialchars on my array value, but it didn't work, htmlspecialchars works when I use it manully; Here is my code:

 $new[] = "<a href='test'>Test</a><li><div>";
 var_dump(array_walk_recursive($new,'htmlspecialchars')); // true
 var_dump($new) ; // no change
Yuga
  • 125
  • 2
  • 9

2 Answers2

2

That is because the original array is not modified unless you modify it yourself in the callback function.

Your callback function is basically:

function($item, $key) {
    htmlspecialchars($item);
}

So while the function is called, nothing is stored and the original array is not changed.

If you want to modify the value in the function, you can pass it by reference:

function(&$item, $key) {
    $item = htmlspecialchars($item);
}

So the result would look like:

 $new[] = "<a href='test'>Test</a><li><div>";
 array_walk_recursive($new, function(&$item, $key) {
        $item =  htmlspecialchars($item);
 });
 var_dump($new) ; // change!

You can of course define a separate function if you would prefer that.

jeroen
  • 91,079
  • 21
  • 114
  • 132
1

In the definition of array_walk_recursive:

array_walk_recursive — Apply a user function recursively to every member of an array

So you need to create a user defined function that uses htmlspecialchars like this:

$new[] = "<a href='test'>Test</a><li><div>";
array_walk_recursive($new, "specialChars");
var_dump($new);

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

And this will print:

array (size=1)
  0 => string '&lt;a href='test'&gt;Test&lt;/a&gt;&lt;li&gt;&lt;div&gt;' (length=56)
Osama Sayed
  • 1,993
  • 15
  • 15