Monday, 13 August 2018

How to Create Comma Separated List From an Array in PHP?

Problem:

You have an array (see following) with some elements inside. You want to create a string joining the elements of the array with commas.
<?php
$week_day = array(“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”);
?>

Solution:

PHP built-in function implode() is the perfect match for the solution. The function takes two parameters – the first one works like glue and the second one is an array. Using the glue, the function joins all the array-elements of the second parameter and returns it as a string. See it in action-
1
2
3
4
5
6
7
<pre>
<?php
$week_day = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
$comma_separated_str = implode(", ", $week_day);
echo $comma_separated_str;
?>
</pre>
Output:
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
How it works:The implode() function takes the array $week_day and joins one element to its next with the glue (comma) and returns the string you see in the output.

0 comments:

Post a Comment