I have this array
Array ( [13] => 500 [16] => 1000 )
Array ( [12] => 1 [13] => 1111 )
how can I make them a string as this shape
13 500, 16 1000
12 1, 13 1111
I have this array
Array ( [13] => 500 [16] => 1000 )
Array ( [12] => 1 [13] => 1111 )
how can I make them a string as this shape
13 500, 16 1000
12 1, 13 1111
This code will solve your issue.
$array = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach ($array as $key => $val) {
echo " ".$key ." ". $val." ,";
}
$input = [13 => 500, 16 => 1000];
$output = implode(', ', array_map(
function ($v, $k) {
return $k . " " . $v;
}, $input, array_keys($input))
);
var_dump($output);
Using foreach
$input = [13 => 500, 16 => 1000];
$output = "";
foreach ($input as $k => $v) {
$output .= $k . " " . $v . ", ";
}
$output = rtrim($output, ", ");
var_dump($output);
assuming you searching for a function with multiple pair array values (as you describe) and each result should be the format: key1[sp]val1,[sp]key2[sp]val2 and you want an array of all these values to use later i did this function:
<?php
function ar(){
$a=func_get_args();
foreach($a as $ar){
$s='';
$i=0;
$s='';
foreach($ar as $ch =>$vl){
$s.=$ch.' '.$vl;
if($i<count($ar)-1){
$s.=', ';
}
$i++;
}
$res[]=$s;
}
return $res;
}
/* output values by sending multiple arrays to parse */
var_dump(ar(
[13 => 500,16=> 1000]
,[12 => 1,13 => 1111]
));
?>