Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

RSS Latest posts from my personal blog


Most viewed posts


Subscribe to RSS feed


Convert comma separated values to array in PHP

Stanislav KhromovStanislav Khromov

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

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
LinkedIn
Twitter
WordPress.org Profile
Visit my other blog

Comments 4
  • Lamine
    Posted on

    Lamine Lamine

    Reply Author

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

    Thanks for the post


  • shruti
    Posted on

    shruti shruti

    Reply Author

    Hi ,I did not get result same like array(‘foo’,’bar’,’baz’);. kindly advice


  • pricereduc
    Posted on

    pricereduc pricereduc

    Reply Author

    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
    )