Imploding an associative array in PHP

For me the best and simplest solution is this:

$string = http_build_query($array, '', ',');

http_build_query (php.net)


There is a way, but it's pretty verbose (and possibly less efficient):

<?php
$array = Array(
  'foo' => 5,
  'bar' => 12,
  'baz' => 8
);

// pre-5.3:
echo 'The values are: '. implode(', ', array_map(
   create_function('$k,$v', 'return "$k ($v)";'),
   array_keys($array),
   array_values($array)
));

echo "\n";

// 5.3:
echo 'The values are: '. implode(', ', array_map(
   function ($k, $v) { return "$k ($v)"; },
   array_keys($array),
   array_values($array)
));
?>

Your original code looks fine to me.


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));

Tags:

Php