How to Create Comma Separated List from an Array in PHP?
Last Updated :
18 Sep, 2024
Improve
The comma-separated list can be created by using implode() function. The implode() is a builtin function in PHP and is used to join the elements of an array.
Syntax:
string implode( separator, array )
Return Type:
The return type of implode() function is string. It will return the joined string formed from the elements of array.
Example 1: This example adds comma separator to the array elements.
<?php
// Declare an array and initialize it
$Array = array( "GFG1", "GFG2", "GFG3" );
// Display the array elements
print_r($Array);
// Use implode() function to join
// comma in the array
$List = implode(', ', $Array);
// Display the comma separated list
print_r($List);
?>
Output
Array ( [0] => GFG1 [1] => GFG2 [2] => GFG3 ) GFG1, GFG2, GFG3
Example 2:
<?php
// Declare an array and initialize it
$Array = array(0, 1, 2, 3, 4, 5, 6, 7);
// Display the array elements
print_r($Array);
// Use implode() function to join
// comma in the array
$List = implode(', ', $Array);
// Display the comma separated list
print_r($List);
?>
Output
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 ) 0, 1, 2, 3, 4, 5, 6, 7
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.