Easy way to parse comma separated item in PHP

Easy way to parse comma separated item in PHP

Today We are going to learn about PHP Parsing. Using the PHP script we can easily extract the individual elements from a comma-separated list. PHP has a useful function called explode() that can convert a comma-separated (string) lists into an array. Lets check an example.

– Easy way to parse comma separated item in PHP:

The following example clearly illustrates this process that the explode() function scans the string for the delimiter( like- comma(,), at-the-rate(@),star(*) ) and cuts out the pieces around it, placing them in an one dimensional array.

Once the list items have been extracted we can use the foreach() function to show them as individual item.

// define a comma separated list

$string= "cat,dog,hen,tiger,pigeon,camel";

// decompose string into array 

// using comma as delimiter

$exploded_string= explode(",", $string);

// output:
//array(0=>'cat',1=>'dog',2=>'hen',3=>'tiger',4=>'pigeon',5=>'camel')

// print individual elements

foreach ($exploded_string as $key=>$value) {
    echo $value . "\n";
}
// output:
//cat
//dog
//hen
//tiger
//pigeon
//camel

Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top