Last Updated on April 5, 2024 by Roshan Parihar
To convert comma string to array in PHP, you have to use the explode()
function. You can also use the preg_match()
function of PHP to change comma-separated strings into an array.
Both functions are useful for the conversion. However, the ways of using them are different which you will see in the below examples. Each example contains the result immediately below it.
Let’s see with the examples given below.
How to Change Comma Separated String to Array in PHP
There are two methods of getting the conversions given here.
Using explode() to Split Comma Delimited String into Array in PHP
The explode function breaks the string and creates an array with it in PHP. It splits the string wherever the comma separation occurs. The function takes the first argument as a comma(,) and the second argument is the comma-separated string variable.
1 2 3 4 5 6 |
<?php //Use explode() function text $string = "red,blue,green"; $str_arr = explode (",", $string); print_r($str_arr); ?> |
Output
The above output shows the converted array using the explode function of PHP. There are three elements present in the array. The print_r()
function prints the array with its elements.
preg_split() Function of PHP
Similarly, you can use the preg_split()
function. It takes two arguments the first is the regular expression. The second argument contains the comma-separated string.
1 2 3 4 5 6 |
<?php //Use preg_split() function text $string = "yellow,pink,brown"; $str_arr = preg_split ("/\,/", $string); print_r($str_arr); ?> |
Output
You will get a similar array conversion of the comma-separated values as shown in the output. The print_r()
function gives the print of the resulting array with its elements. If you want to get more details array elements in the output with its data type, you can use the var_dump()
function of PHP.
When you have comma-separated string then array conversion makes it easier to operate on elements. You can perform several operations like searching, sorting, element removal, and more after conversion to an array.
Learn more on PHP with our detailed PHP tutorial and start coding.