Skip to content

PHP array_map for multidimensional arrays

Last updated on January 31, 2018

Array map is one of the interesting PHP’s array function. But it will not work with multidimensional arrays as expected.So in this post, I would like to share a simple alternative technique for array_map(). Our function will work like array_map but it will support multidimensional arrays.

 function my_array_map($function, $arrary)
{
  $result = array();
  foreach ($arr as $key => $val)
  {
      $result[$key] = (is_array($val) ? my_array_map($function, $val) : $function($val));
  }
  return $result;
}

Here we used recursive function methodology and the Ternary Operator syntax.

How to use

you can use my_array_map just like as array_map().

 $array = array('test ',array('website' => 'arjun php '));
  my_array_map('trim',$array);

That’s it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments