Convert comma separated values to array in PHP

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');

4 thoughts on “Convert comma separated values to array in PHP

  1. Lamine

    Useful post. I think you should replace the comma at line 10 by the $separator variable.

    Thanks for the post

    Reply
  2. pricereduc

    We can also add a third argument for explode function, this argument is an int type and can be positive or negative

    It’s useful if you want to limit the number of elements, therfore the last one will be the rest of the string

    Example:
    $separator = “,”;
    $string=”w,x,y,z”;
    $limit = 2;
    $vals = explode($separator, $string,$limit);

    print_r($vals); will show this output

    Array
    (
    [0] => w
    [1] => x,y,z
    )

    Reply

Leave a Reply

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

Markdown is allowed in comments.