How to Convert String to Array Conversion in Laravel?
Hi Developer,
I am going to explain to you example of laravel string to array conversion. We will use how to convert string to array in laravel. This article goes in detailed on how to convert string to array in laravel blade. In this article, we will implement a how to convert string to array in laravel blade.
I will give you the following two examples of laravel string to array conversion in controller file and blade file.
1. How to Convert String to Array in Laravel Controller
2. How to Convert String to Array in Laravel Blade
we will use explode() to convert string into array in laravel. you can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions. so, lt's see one by one example
1. How to Convert String to Array in Laravel Controller
Controller File:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$string = "One, Two, Three, Four, Five";
$stringArray = explode(",", $string);
dd($stringArray);
}
}
Output:
array:5 [
0 => "One"
1 => " Two"
2 => " Three"
3 => " Four"
4 => " Five"
]
1. How to Convert String to Array in Laravel Blade
Blade File:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
@php
$string = "One, Two, Three, Four, Five";
$stringArray = explode(",", $string);
@endphp
<ul>
@foreach ($stringArray as $value)
<li>Value: {{ $value }}</li>
@endforeach
</ul>
</body>
</html>
Output:
One
Two
Three
Four
Five
I hope it can help you...