Search code examples
phphtmlspecialchars

array_walk_recursive can't work when I use function htmlspecialchars?


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

Solution

  • 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)