Convert comma separated string to array and test for entries
Ensure no trailing comma that will produce a blank final array entry
$MyCommaSeperatedString = "abc,def,ghi,";
//Ensure there is no trailing comma
$MyCommaSeperatedString = rtrim(trim($MyCommaSeperatedString), ",");
$MyArray = ($MyCommaSeperatedString === '') ? [] : explode(',', $MyCommaSeperatedString);
//(No commas will result in the text in the string being in an array of length 1, an empty string will result in an empty array)
print_r($MyArray);
//$MyCommaSeperatedString = "abc,def,ghi,";
//Will output: Array ( [0] => abc [1] => def [2] => ghi )
//$MyCommaSeperatedString = "";
//Will output: Array ()
Examples
$MyCommaSeperatedString = "abc,def,ghi";
$MyArray = ($MyCommaSeperatedString === '') ? [] : explode(',', $MyCommaSeperatedString);
print_r($MyArray);
//Will output: Array ( [0] => abc [1] => def [2] => ghi )
$MyCommaSeperatedString = "abc,def,ghi,";
$MyArray = ($MyCommaSeperatedString === '') ? [] : explode(',', $MyCommaSeperatedString);
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 = ($MyCommaSeperatedString === '') ? [] : explode(',', $MyCommaSeperatedString);
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
Add new value to a comma separated string
if ($MyCommaSeperatedString === '')
$MyCommaSeperatedString = $MyNewValue;
else
$MyCommaSeperatedString .= ',' . $MyNewValue;
