0

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

Lemon Kazi
  • 3,308
  • 2
  • 37
  • 67

2 Answers2

4

//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;
AmmyTech
  • 738
  • 4
  • 10
2

You can use array_column() for that, and then use implode() to comma separated string.

Your code might look something like this,

$arr = array (array ('allergy' => 'test'),array ('allergy' => 'test1') );
$arr=array_column($arr,"allergy");
$str = implode (",", $arr);
echo $str;

array_column() returns the values from a single column of the input, identified by the second parameter(column_key).

Demo: https://eval.in/620454

Alok Patel
  • 7,842
  • 5
  • 31
  • 47