Say I have an array:
$array = Array(
\'foo\' => 5,
\'bar\' => 12,
\'baz\' => 8
);
And I\'d like to print a line of text in m
For me the best and simplest solution is this:
$string = http_build_query($array, '', ',');
http_build_query (php.net)
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));
Taking help from the answer of @linepogl, I edited the code to make it more simple, and it works fine.
function array_map_assoc($array){
$r = array();
foreach ($array as $key=>$value)
$r[$key] = "$key ($value)";
return $r;
}
And then, just call the function using
echo implode(' , ', array_map_assoc($array));
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)
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.
You could print out the values as you iterate:
echo 'The values are: ';
foreach ($array as $key => $value) {
$result .= "$key ($value),";
}
echo rtrim($result,',');