Search code examples
phparraysloopshtmlspecialchars

Execute htmlspecialchars on a multi level array


I am trying to find a way to loop through all my data and remove all the HTML special characters. The problem is my data can have values that are arrays which can themselve have 5 or 6 sub arrays. Could someone please help me with a good method to do this. This is the code I have been working with so far but it skips all the sub arrays values.

    foreach($view['data'] as $key => $value){
        // Check if Array
        if(!is_array($value)){
            $view['data'][$key] = htmlspecialchars($value);
        }
    }

Solution

  • You can use the array_walk_recursive() function - http://php.net/manual/en/function.array-walk-recursive.php

    array_walk_recursive($view['data'], function(&$item) {
      $item = htmlspecialchars($item);
    });