Home > Enterprise >  Apply function to every element of a multidimensional array
Apply function to every element of a multidimensional array

Time:05-15

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?

CodePudding user response:

function recurse(array $array): array {
  $result = [];
  foreach ($array as $key => $value) {
    $newKey = is_string($key) ? strtoupper($key) : $key;
    if (is_array($value)) {
      $result[$newKey] = recurse($value);
    } elseif (is_string($value)) {
      $result[$newKey] = strtoupper($value);
    } else {
      $result[$newKey] = $value;
    }
  }
  return $result;
}

$array = [
    'document'  => [
        'Value1',
        'Value2',
        'Value3'
    ],
    'document2' => [
        'Value21',
        'Value22',
        'document2' => [ 'Value221', 222, 'Value223' ],
        23
    ]
];

$result = recurse($array);

print_r($result);

CodePudding user response:

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.

  • Related