Imploding an associative array in PHP

The problem with array_map is that the callback function does not accept the key as an argument. You could write your own function to fill the gap here:

function array_map_assoc( $callback , $array ){
  $r = array();
  foreach ($array as $key=>$value)
    $r[$key] = $callback($key,$value);
  return $r;

Now you can do that:

echo implode(',',array_map_assoc(function($k,$v){return "$k ($v)";},$array));

Leave a Comment