- PHP

How to make an array from comma separated string in PHP

Use explode() function.

explode(',', $commaSeparatedString);

Example 1:

Make an array from comma separated string with spaces.

<?php

$names = 'Anna, Kate, Frank';
$namesArray = explode(', ', $names);

print_r($namesArray);

?>

Output:

Array ( [0] => Anna [1] => Kate [2] => Frank )

Example 2:

Make a list from comma separated string.

<?php

$animals = 'snake,eagle,lion';

$animalsArray = explode(',', $animals);

echo '<ul>';
    foreach($animalsArray as $animal) {
        echo '<li>'.$animal.'</li>';
    }
echo '</ul>';

?>

Output:

  • snake
  • eagle
  • lion