- PHP

Split a comma separated string into an array in PHP

To do this, use the explode() function with the separator , and string as its arguments.

$commaSeparatedArray = explode(",", $yourVariable);

or

$commaSeparatedArray = explode(", ", $yourVariable);

if the array contains also spaces after commas.

Example:

<?php

$cities = "New York, Los Angeles, Chicago, Houston, Phoenix, Philadelphia";
$commaSeparatedArray = explode(", ", $cities);

var_dump($commaSeparatedArray);

?>

Output:

array(6) { [0]=> string(8) "New York" [1]=> string(11) "Los Angeles" [2]=> string(7) "Chicago" [3]=> string(7) "Houston" [4]=> string(7) "Phoenix" [5]=> string(12) "Philadelphia" }