Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel array to string conversion

I want to convert my array to comma separated string.

my array

array:2 [
  0 => array:1 [
    "name" => "streaming"
  ]
  1 => array:1 [
    "name" => "ladies bag"
  ]
]

I want result as streaming,ladies bag

like image 467
Beffing Avatar asked Mar 21 '16 14:03

Beffing


2 Answers

maybe a little simpler like that

$string=implode(",",$your_array);
like image 57
Garry Avatar answered Sep 29 '22 12:09

Garry


Since these look like Laravel collections converted to arrays, I would suggest using the inbuilt implode() method.

As per the docs:

$collection = collect([
    ['account_id' => 1, 'product' => 'Desk'],
    ['account_id' => 2, 'product' => 'Chair'],
]);

$collection->implode('product', ', ');

// Desk, Chair

Reference: https://laravel.com/docs/master/collections#method-implode

However, if they're ordinary arrays, and since it's not a single array, you'd have to write a foreach or flatten it with array_column() before running PHP's ordinary implode() function.

like image 22
Joel Hinz Avatar answered Sep 29 '22 13:09

Joel Hinz