Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imploding an associative array in PHP

Tags:

php

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?

like image 878
Alec Avatar asked Jul 02 '11 12:07

Alec


People also ask

What is implode array in PHP?

Definition and Usage. The implode() function returns a string from the elements of an array. Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. Note: The separator parameter of implode() is optional.

How do you implode an array of arrays?

PHP Implode Function The implode function in PHP is used to "join elements of an array with a string". The implode() function returns a string from elements of an array. It takes an array of strings and joins them together into one string using a delimiter (string to be used between the pieces) of your choice.

How does implode work in PHP?

The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function. If we have an array of elements, we can use the implode() function to join them all to form one string.

How do you convert associative array to string?

To convert an array to a string, one of the common ways to do that is to use the json_encode() function which is used to returns the JSON representation of a value.


1 Answers

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)); 
like image 152
linepogl Avatar answered Sep 29 '22 22:09

linepogl