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?
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.
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With