W3docs

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

On this page, we are going to provide you with comprehensive information about a common PHP issue: how to split a comma delimited string into an array.

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

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

?>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

The output will look like this:

php explode output

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

Describing PHP explode

The explode() function is supported on <kbd class="highlighted">PHP 4</kbd>, <kbd class="highlighted">PHP 5</kbd>, <kbd class="highlighted">PHP 7</kbd>, and <kbd class="highlighted">PHP 8</kbd>. 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.