A short snippet you can use:
/**
* @param $string - Input string to convert to array
* @param string $separator - Separator to separate by (default: ,)
*
* @return array
*/
function comma_separated_to_array($string, $separator = ',')
{
//Explode on comma
$vals = explode($separator, $string);
//Trim whitespace
foreach($vals as $key => $val) {
$vals[$key] = trim($val);
}
//Return empty array if no items found
//http://php.net/manual/en/function.explode.php#114273
return array_diff($vals, array(""));
}
Usage:
$array_one = comma_separated_to_array("foo,bar,baz");
$array_two = comma_separated_to_array("1, 2, 3 ");
Result:
array('foo','bar','baz');
array('1','2','3');