How to Convert Comma String to Array in PHP

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.


Array ( [0] => red [1] => blue [2] => green )

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.


Array ( [0] => yellow [1] => pink [2] => brown )

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.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.