How to do array-to-string conversion in Laravel Controller

Laravel has many built-in functions that greatly ease many tasks and coding operations. One such is the array-to-string conversion we can do. in a Laravel Controller.

array-to-string conversion

The implode() function is used for this task. It concatenates an array’s elements into a single string using a specified delimiter. implode() is a built-in method and can easily convert an array into a string.

Consider the code snippet below that shows how we can use the implode() function for array-to-string conversion in a Laravel Controller.


namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ArrayController extends Controller
    public function arrayMethod(Request $request)
        $array = ['Hello', 'Scratch', 'Coding'];
        $delimiter = ' - '; // You can specify the delimiter according to your requirements

        $string = implode($delimiter, $array);

        return $string;

The code snippet above. shows the arrayMethod function. Here, $array has three elements, ‘Hello’, Scratch’, ‘Coding’, and a delimiter ‘ – ‘ is specified. The implode function is then called and two parameters are passed to it. One is the delimiter and then the array. So, the implode function will convert the array of elements into a string and separate each element by a -.

The output of the code above will be as shown below.

"Hello - Scratch - Coding"

Leave a Comment