Assuming we are given a comma-separated fruit list in string format:
$fruits = "orange, banana, apple";
Now, we want to convert the list into a PHP array to further processing it. That is what this short how-to article is about. We will guide you on how to convert from string to array in PHP.
We also had another detailed guide written on multiple methods to do the opposite – convert from array to string in PHP.
- How to convert from array to string in PHPShort guide on converting from array to string in PHP easily that works.
Quick solution
Here are the quick solution for the above question:
$fruitsArray = explode( ',', $fruits );
This line will:
- Take the comma
,
as the separator - Separate the string into a
$fruitsArray
array with 03 elements,orange
,banana
,apple
.
To know more details on how it works, here are the detailed guide.
To convert from string to array in PHP
Converting from string to array in PHP, or in another meaning, is to separate the string into parts and join these parts into an array using boundaries formed by a separator.
The simplest way to do that is by the built-in explode
function.
Using explode
function
We can easily use the PHP explode
function to separate a string from PHP and convert it into array. The function syntax is:
explode(string $separator, string $string, int $limit = PHP_INT_MAX)
In this function:
$separator
is the separator for the function to split the string into parts.$string
is the string to be converted- (Optional)
$limit
is the maximum of elements to be split and converted into array from the string. By default, its value equalsPHP_INT_MAX
which is the largest integer supported by your current PHP build.
If you use$limit
, the last element of the converted array will contain the rest of the string that is not converted.
The return of the explode
function will be the converted array.
Examples
For the beginning question on the $fruits
fruit list, we will use the comma (,
) as the function separator, because it is also the main separator in the string.
// Convert $fruits list into array
$fruitsArray = explode( ',', $fruits );
We will get the result as an array with the expected elements.
print_r($fruitsArray);
// Output
Array
(
[0] => Orange
[1] => Banana
[2] => Apple
)
Final thoughts
The explode
function is very powerful and easy to use to convert string to array in PHP with a separator.