15

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

Nabin Kunwar
  • 1,965
  • 14
  • 29
Beffing
  • 243
  • 1
  • 3
  • 7

5 Answers5

14

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.

Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
  • A side note: it can be also used on Fluent/Eloquent collections. e.g.: $this->student->find(auth()->user()->id)->get()->studentFavouriteSubjects()->implode('subject_id', ', '); – Jeffz Jul 02 '19 at 00:55
8

maybe a little simpler like that

$string=implode(",",$your_array);
Garry
  • 81
  • 1
  • 2
2

Use a foreach loop twice to segregate the array and use substr to remove the last character

$string = '';

foreach($your_array as $a)
{    
    foreach($a as $b=>$c)
    {
        $string .= $c.',';
    }
}

$solution = substr($string,0,-1);

print_r($solution);
treyBake
  • 6,440
  • 6
  • 26
  • 57
1

U could try a simple foreach and add a comma value after every iteration.

 $string='';
 foreach ($your_array as $value){
    $string .=  $value.',';
 }
Raul H
  • 285
  • 3
  • 19
  • Not only that solution will always have a trailing comma, the OP wants to flatten a multidimensional array – Fabio Antunes Mar 21 '16 at 16:17
  • in my case i have jwt token in laravel generated by passport and i cant save it in my db and this error happened but with this function i can convert it. but why virgool character at the end – saber tabatabaee yazdi Oct 14 '19 at 13:29
0

I have tried the following code to convert array to string in laravel blade file and it works fine .

<body>
  <center>
     <h1> LARAVEL ARRAY TO STRING CONVERSION </h1>
  </center>
  <div class="main">
     <?php
        $arr=array("this","is","an","array");
        
        echo "array elements are"."<br>";
        
        foreach($arr as $value)
         echo $value."<br>";
        
        echo "The string is "."<br>";
        ?>
     @foreach($arr as $value)
     {!! $value !!}
     @endforeach
  </div>
kishan maharana
  • 623
  • 8
  • 10