Categories
Tools

PHP comma separated string to list

Last updated on November 16th, 2015 at 09:39 am

Click to rate this tutorial!
[Total: 3 Average: 4.7]

This script will show you how to separate a string that contains comma, semicolon etc and then list it accordingly. Here we are using explode() and also empty(). If there is an empty space between two comma or semicolon then that is automatically discarded. Here is how the code looks.

$country = "USA, canada, brazil, india, ,australia, malaysia, singapore";
$arrCountry = explode(",",$country);
foreach($arrCountry as $v){
$d=trim($v);
if(!empty($d))
{  echo $d."<br />";
  }
}

Here i have purposefully given an empty area between INDIA and AUSTRALIA and that is discarded during the execution.Here is how the O/P looks

USA
canada
brazil
india
australia
malaysia
singapore

Click to rate this tutorial!
[Total: 3 Average: 4.7]

Leave a Reply

Your email address will not be published.