I've an array to reduce to string, but I've to do MANY times so I would like to use some array PHP function (some combination of array_walk, array_reduce,...) but none fit my needs, but I belive there's a solution that I miss. The code have to be PHP5.6 compliant too.
$list =[
'k1' => 'vA1 vA2 vA2',
'k2' => 'vB1 vB2 vB2',
'k3' => '',
'k4' => 'vC1 vC2 vC2',
'k5' => NULL,
'k6' => 'vD1 vD2 vD2',
];
function reduce($list){
$_buff="";
$_sep="";
foreach ($list as $k => $v){
if($v===null){
continue;
}
$_buff.="$_sep$k $v";
$_sep="; ";
}
return $_buff;
}
echo reduce($list)."
";
The expected result is
k1 vA1 vA2 vA2; k2 vB1 vB2 vB2; k3 ; k4 vC1 vC2 vC2; k6 vD1 vD2 vD2
Please note the different behavior if value is an empty string or null.