Imploding an Associative Array

Display formatted content from an associative array with implode()


In the previous article, I said that implode() only works on simple, numeric arrays, but what if you want to do something similar with an associative array of keys and values. You can create a new array that implode() will like and run impolde() on that array. In this article we'll see how.


Let's take this array from the previous article:

$nameArray = array(
  'BobRay' => 'bobray@somewhere.com',
  'JohnDoe' => 'johndoe@gmail.com',
  'JaneRoe' => 'janeroe@aol.com',
);

We want to print a line of text to display the results like this:

The values are: BobRay (bobray@somewhere.com), JohnDoe (johndoe@gmail.com), JaneRoe (janeroe@aol.com)

We can't call implode() directly on the associative array, but we can create a new simple numeric array that will give us what we want when we use implode() on it.


The Code

Here's our snippet. Notice that at the top of the snippet we've included the array of names we showed above, though it could just as well have come from somewhere else.

$output = '';

$nameArray = array(
  'BobRay' => 'bobray@somewhere.com',
  'JohnDoe' => 'johndoe@gmail.com',
  'JaneRoe' => 'janeroe@aol.com',
);

/* Create the new array */
$users = Array();

/* Add each user to the new array */
foreach ($nameArray as $key => $value) {
  $users[] = $key  . ' (' . $value . ')';
}
$output =  'The values are: '. implode(', ',$users);
return $output;

Because of the way PHP handles variable in double quotes, we could also use this line inside the foreach() loop:

$users[] = "$key ($value)";

The $key and $value variables will be replaced, the space and the two parentheses will be left as is. Which method you use is a matter of personal preference.

It's possible to do this in a custom function using a combination of array_map(), array_keys(), and array_values(), but I consider it ugly, inefficient, and difficult to read. It also depends on the version of PHP. For the curious, here it is:

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

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

// PHP 5.3+:
$output =  'The values are: '. implode(', ', array_map(
   function ($k, $v) { return "$k ($v)"; },
   array_keys($array),
   array_values($array)
));

return $output;

Here is a another interesting version offered up by Jason Coward (OpenGeek), using array_walk and a PHP closure. It also requires PHP 5.3 and my research suggests that it will be slightly slower than the original iterator version at the top of this article, though I haven't run any benchmarks myself.

$array = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
);
$flattened = $array;
array_walk($flattened, function(&$value, $key) {
    $value = "{$key} ({$value})";
});
echo 'The values are ' . implode(', ', $flattened);


Comments (2)

  1. MellFotoStudioOct 05, 2015 at 07:05 AM

    As an aside, if all you need to do is to pass the array in text form somewhere else, you can avoid parsing it altogether by using the serialize() function - it will walk through the array and represent it as a flat text string. You can then use unserialize() to restore the original array - key associations and all.

    In fact, you can serialize() any PHP variable - even objects! However, it gets complicated for more structured objects - in order to make sure that your object will be correctly serialized() and unserialized(), you need to include two methods - __sleep() and __wakeup() - that will perform any actions you deem necessary before/after these procedures (they could, for example, close up all open handles and sanitize any delicate data structures that don't take kindly to compacting in this manner).

    Keep in mind that serialized() entities may contain sensitive characters (like null bytes), so it's never a good idea to store them in plain text - I almost invariably wrap them in base64_encode() before storage or transmission.

  2. Bob RayOct 09, 2015 at 11:42 PM

    Good tip. Thanks! :)


Please login to comment.

  (Login)