Skip to content

Apply function to every element of a multidimensional array

I have a multidimensional array like this (please ignore the strlen):

array(2) {
  ["document"]=>
    array(16) {
      [0]=>
      string(14) "Value1"
      [1]=>
      string(4) "Value2"
      [2]=>
      string(30) "Value3"
  ...

And I want to call “strtoupper” for every element (Value1, Value2, etc.) on each level of the multidimensional array (document, etc.).

I tried array_walk_recursive($array, "strtoupper"); but it doesn’t work. But why, what can I do?

Answer

As strtoupper does not change the original value, but returns new value instead, you should do this:

array_walk_recursive(
    $array, 
    // pass value by reference. 
    // Changing it will also reflect changes in original array
    function (&$value) { $value = strtoupper($value); } 
);

Simple fiddle.

Also this hint is described in manual, see the note on callback parameter description.