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

0

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

array_column will work for php version >= 5.5
Why do you answer the same question twice: stackoverflow.com/a/38673562/3933332 ?
@AlokPatel but it's not working in my application and my array was different.
I forgot @Rizier123, My bad. Sorry!
@LemonKazi What is not working for you?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.