Convert comma separated string to array and test for entries

Ensure no trailing comma that will produce a blank final array entry
    $MyCommaSeperatedString = rtrim(trim("abc,def,ghi,"), ",");      //Ensure there is no trailing comma
    $MyArray = explode(',', $MyCommaSeperatedString);    //Convert to array (No commas will result in the text in the string being in an array of length 1)
    print_r($MyArray);
    //Will output: Array ( [0] => abc [1] => def [2] => ghi )
Examples
    $MyCommaSeperatedString = "abc,def,ghi";
    $MyArray = explode(',', $MyCommaSeperatedString);    //Convert to array (No commas will result in the text in the string being in an array of length 1)
    print_r($MyArray);
    //Will output: Array ( [0] => abc [1] => def [2] => ghi ) 
    

    $MyCommaSeperatedString = "abc,def,ghi,";
    $MyArray = explode(',', $MyCommaSeperatedString);    //Convert to array (No commas will result in the text in the string being in an array of length 1)
    print_r($MyArray);
    //Will output: Array ( [0] => abc [1] => def [2] => ghi [3] => )
    

    $MyCommaSeperatedString = rtrim(trim("abc,def,ghi,"), ",");      //Ensure there is no trailing comma
    $MyArray = explode(',', $MyCommaSeperatedString);    //Convert to array (No commas will result in the text in the string being in an array of length 1)
    print_r($MyArray);
    //Will output: Array ( [0] => abc [1] => def [2] => ghi )

Convert array into comma separated string

    $MyArray = array();
    $MyArray[] = 'abc';
    $MyArray[] = 'def';
    $MyArray[] = 'ghi';
    $MyCommaSeperatedString = implode(',', $MyArray);      //Convert array to comma seperated string
    echo $MyCommaSeperatedString . "<br>";
    //Will output: abc,def,ghi
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *