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.

0

1 Answer 1

2

You could simply make use of array_walk_recursive:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Also, can I just write array_walk_recursive($input,'htmlentities') ?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.