How to convert string to array using PHP
Last Updated on Dec 19, 2022 - Written By Torikul Islam
A string is a set of character. You can split a string to an array using PHP built-in explode() function.
Now I am going to convert the array elements into string from an example array. The explode() function can breaks a string into an array. This function is binary-safe.
Syntax
explode(separator,string)
You need to provide two parameter here. But you can use another optional parameter.
1. Separator: This parameter specifies where to break the string. It cannot be an empty string.
2. String: This parameter indicate from where you want to split.
3. Limit: It specifies the number of array elements to return. This is an optional parameter.
Note: you can use variable in the replacement of parameters.
Example: Convert string to array
Example 1: Break string by space
<?php
//input string
$string = "color1 color2 color3 color4 color5 color6 color7 color8";
//breaking string
$color = explode(" ", $string);
//showing results
echo $color[0]; // Output: color1
echo $color[1]; // Output: color2
Example 2: Break string by comma
<?php
//input string
$string = "color1, color2, color3, color4, color5, color6, color7, color8";
//breaking string
$color = explode(",", $string);
//showing results
echo $color[2]; // Output: color3
echo $color[3]; // Output: color4
//showing result
print_r($color);
Output:
Array (
[0] => color1
[1] => color2
[2] => color3
[3] => color4
[4] => color5
[5] => color6
[6] => color7
[7] => color8 )
The output methods I provide avobe may not the proper methods while working with projects. You need to use foreach loop to perfect results. Please see the example below.
Example 3: Showing converted output with foreach loop
<?php
//input string
$string = "color1 color2 color3 color4 color5 color6 color7 color8";
//breaking string
$color = explode(" ", $string);
//generating output
foreach($color as $output){
echo $output.'<br>';
}
Output:
color1
color2
color3
color4
color5
color6
color7
color8