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-
<pre> <?php $week_day = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); $comma_separated_str = implode(", ", $week_day); echo $comma_separated_str; ?> </pre>
[wpdm_file id=69]
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.