PHP apply function recursively to every member of an array

Apply a function or required process recursively to every member of multidimensional array. Applies the function or required process to each element of the array. This function will recurse into deeper arrays. multiDimArrayMap() will make loop on given array and apply specific process or function on given array element.

Function will also work for inner array exist in multidimensional array. Let’s check process with example step by step.

PHP apply function recursively to every member of an array
PHP apply function recursively to every member of an array

Multidimensional array:

$multiDimArr = array(
  'name' => 'Developer',
  'hobby' => array(
    '1' => 'Surfing',
    '2' => 'Cricket'
  ),
  'simplearr' => array(
    'value1', 'value2', 'value3'
  )
);

Funtction for multidimension array map:

Function make loop on parameter array and check element. If element is also another array it will make recursive call to function again else it apply required function or process to element.

function multiDimArrayMap($arr)
{
  $retArr = array();
  foreach($arr as $k => $v)
  {
    if(is_array($v))
    {
      $retArr[$k] = multiDimArrayMap($v);
    }
    else
    {
      //Apply required process on value
      //Here 'strtoupper' function applied
      $retArr[$k] = strtoupper($v);
    }
  }
		
  return $retArr;
}

Use of multidimension array map function:

$finalArr = multiDimArrayMap($multiDimArr);
print_r($finalArr);