Lemon Kazi Lemon Kazi - 3 months ago 10
PHP Question

array to comma separated string for selected key

Hi I have an array just like below

$arr = array ( [0] => Array ( [allergy] => test ),[1] => Array ( [allergy] => test1 ) );


Here from that array I just want
allergy
value as comma separated string like
test,test1


I tried implode but it's not working

$arr = array ( [0] => Array ( [allergy] => test ),[1] => Array ( [allergy] => test1 ) );
$str = implode (", ", $arr);
echo $str;


here is my sample

Answer

//array_column will work from php version 5.5,

$arr = array ( '0' => Array ( 'allergy' => 'test' ),'1' => Array ( 'allergy' => 'test1' ) );
$str = '';
foreach($arr as $row){
    $str .=$row['allergy'].',';
}
$str = trim($str,',');
echo $str;
Comments