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

3

5 Answers

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:

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.

1

maybe a little simpler like that

$string=implode(",",$your_array);

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);
0

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

 $string=''; foreach ($your_array as $value){ $string .= $value.','; }
2

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> <?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>

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like