0

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 :(

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.