Friday, October 24, 2025
HomeLanguagesSplit a comma delimited string into an array in PHP

Split a comma delimited string into an array in PHP

Given a long string separated with comma delimiter. The task is to split the given string with comma delimiter and store the result in an array.

Examples:

Input : neveropen,for,neveropen
Output : Array ( [0] => neveropen [1] => for [2] => neveropen )

Input : practice, code
Output : Array ( [0] => practice [1] => code )

Use explode() or preg_split() function to split the string in php with given delimiter.

PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.
Syntax:

array explode( separator, OriginalString, NoOfElements )

PHP | preg_split() Function: The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.

Syntax:

array preg_split( string $pattern, string 
$subject [, int $limit = -1 [, int $flags = 0 ]] )

Example:




<?php
  
// Use preg_split() function
$string = "123,456,78,000"; 
$str_arr = preg_split ("/\,/", $string); 
print_r($str_arr);
      
// use of explode
$string = "123,46,78,000";
$str_arr = explode (",", $string); 
print_r($str_arr);
?>


Output:

Array
(
    [0] => 123
    [1] => 456
    [2] => 78
    [3] => 000
)
Array
(
    [0] => 123
    [1] => 46
    [2] => 78
    [3] => 000
)

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS