Skip to content

How to Split a Comma Delimited String to an Array with PHP

Almost every developer has been in a situation when it is necessary to split a comma delimited string into an array while working with PHP. This snippet is dedicated to discovering a solution to that issue. In practice, it can be easily accomplished with the help of explode.

Here is an example:

php split a comma delimited string to an array with explode

php
<?php

$myString = "9,[email protected],8";
$myArray = explode(',', $myString);
print_r($myArray);

?>

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

The output will look like this:

php explode output

text
Array ( [0] => 9, [1] => [email protected], [2] => 8 )

Describing PHP explode

The explode() function is supported on PHP 4, PHP 5, PHP 7, and PHP 8. It splits a string into an array using a specified delimiter. The function returns an array of strings, where each element is a substring created by splitting the original string at the delimiter boundaries. It also accepts an optional third limit parameter to restrict the number of returned array elements.

Dual-run preview — compare with live Symfony routes.