views:

37

answers:

1

Hi,

I have this array:

$array = array('a' => 'apple' , 'c' => 'cat', 'ar' => array('d' => 'dog', 'e' => 'elephant'));

Outputting:

Array
(
    [a] => apple
    [c] => cat
    [ar] => Array
        (
            [d] => dog
            [e] => elephant
        )

)

How to I make the values of above nested array upper case while preserving the keys. I tried this:

function upper($str){
  return strtoupper($str);
}

$array_upper = array_map('upper', $array);

But it does not seem to work for nested arrays because here is the result of it:

Array
(
    [a] => APPLE
    [c] => CAT
    [ar] => ARRAY
)

Whereas I want result like this:

Array
(
    [a] => APPLE
    [c] => CAT
    [ar] => ARRAY
        (
            [d] => DOG
            [e] => ELEPHANT
        )

)

Tried with array_walk and array_walk_recursive but using print_r(...) on return array results into 1.

So basically how to apply a callback function to nested array that can be nested to n level. This should be easy but I am missing something :(

+2  A: 

array_walk_recursive() should work, but it modifies the array you pass in and returns a bool, which is why you get 1 printed.

Note that you need to make sure the function you pass as a callback also takes the first parameter (the array element value) as a reference and modifies that rather than returning the modified value. (unlike array_map()), e.g.

function upper(&$str){
    $str = strtoupper($str);
}
Tom Haigh