My Computer Tips

Home | About | Categories | All Tips & Tutorials

Split comma delimeted string using the php explode() function and output results

ID: 345

Category: PHP7

Added: 18th of April 2023

Views: 1,317



Click here to buy PHP books on Amazon
Affiliate Link ⓘ

To split a comma delimited string using PHP we can use the explode() function

The explode() function breaks the string in to an array, which is then assigned to a variable.
We then use a foreach loop to output the results / elements.

<?php
$list="Ubuntu, Lubuntu, Xubuntu, Kubuntu, Manjaro, Fedora, Linux Mint";
$array = explode(",", $list);

foreach ($array as $value)
{
echo $value."<p></p>";
}
?>

If you wanted to sort the elements in alphabetical order you would use the sort() function
<?php
$list="Ubuntu, Lubuntu, Xubuntu, Kubuntu, Manjaro, Fedora, Linux Mint";
$array = explode(",", $list);

sort($array);

foreach ($array as $value)
{
echo $value."<p></p>";
}
?>