PHP Convert String to Array By Comma Example


Share:
Published By: Admin, Published On: Apr 13, 2021, Category: PHP

Hi Guys,

In this blog,I will explain you how to convert string to array by comma delimiter.Use explode() or preg_split() function to split the string in php with given delimiter.

Method : 1

The explode() function is an inbuilt function in PHP which is utilized to split a string in different strings. The explode() function splits a string predicated on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings composed by splitting the original string.

Syntax:
explode(separator,string,limit);
Example
<?php

     // Use explode() function
    $myStr = "Welcome,To,MyWebtuts.com";
    $myArr = explode(',', $myStr);
    print_r($myArr);

?>
Output
Array
(
    [0] => Welcome
    [1] => To
    [2] => MyWebtuts.com
)
Method : 2

Now,Let's see another function to convert string to array by comma delimiter The preg_split() function operates precisely like to split(), except that regular expressions are accepted as input parameters for pattern.

Syntax:
preg_split(pattern, string, limit, flags);
Example
<?php

    // Use preg_split() function
    $string = "Rahul,Kiran,Dharmik,Mehul"; 
    $str_arr = preg_split ("/\,/", $string); 
    print_r($str_arr);

?>
Output
Array
(
    [0] => Rahul
    [1] => Kiran
    [2] => Dharmik
    [3] => Mehul
)

It will help you..

Share: