0

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.

Maciek Semik
  • 1,872
  • 23
  • 43

1 Answers1

2

You could simply make use of array_walk_recursive:

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

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

Jeto
  • 14,596
  • 2
  • 32
  • 46
  • Also, can I just write array_walk_recursive($input,'htmlentities') ? – Maciek Semik Feb 03 '19 at 00:17
  • @MatthewSemik Unfortunately not, because the return value of the callback doesn't matter in that case (contrary to `array_map` for instance). You have to change the value itself, hence the `&` before the parameter. – Jeto Feb 03 '19 at 00:18