Imploding an associative array in PHP

Viewed 45965

Say I have an array:

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

And I'd like to print a line of text in my view like this:

"The values are: foo (5), bar (12), baz (8)"

What I could do is this:

$list = Array();
foreach ($array as $key => $value) {
  $list[] = "$key ($value)";
}
echo 'The values are: '.implode(', ',$list);

But I feel like there should be an easier way, without having to create the $list array as an extra step. I've been trying array_map and array_walk, but no success.

So my question is: what's the best and shortest way of doing this?

8 Answers

Clearly, the solution proposed by Roberto Santana its the most usefull. Only one appointmen, if you want to use it for parse html attributes (for example data), you need double quotation. This is an approach:

Example: var_dump( '<td data-'.urldecode( http_build_query( ['value1'=>'"1"','value2'=>'2' ], '', ' data-' ) ).'></td>');

Output: string '<td data-value1="1" data-value2=2></td>' (length=39)

I do it this way :

  • I firstly define a new array to fill with the values of my existing array
  • I check if my associative array is set and is not empty
  • Then loop on my array and fill the new one with the values
  • After the loop has terminated, i implode the new array

as you can see :

$new_array = [];

if (isset($array) && $array != null) {
    foreach ($array as $el) {$new_array[] = $el->value;}
    $new_array = implode(',', $new_array);
}

echo $new_array;
Related