phparraysmultidimensional-arrayrecursiveiterator

PHP Cleaning up nested arrays with unknown structure


Let's assume I have an array like so:

[1=>[1=>2,2=>"something"],2=>[1,2],3=>"hello"]

The array has a "unorganized" structure with subarrays other values.

I want to run a htmlentities function on each value to make sure nothing bad is inside the values.

I've been reading up on RecursiveIteratorIterator but I cannot find an example of how to use it to apply a function to each value in a quite random nested multidimensional array. Any help is appreciated.


Solution

  • You could simply make use of array_walk_recursive:

    array_walk_recursive($input, function (&$value) {
      $value = htmlentities($value);
    });
    

    Demo: https://3v4l.org/QmRJr