Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create comma separated list from an array in PHP?
Creating a comma-separated list from an array in PHP is efficiently done using the built-in implode() function. This function joins array elements with a specified delimiter string.
Syntax
implode(separator, array)
Parameters
separator: The string to use as a delimiter between array elements (optional, defaults to empty string).
array: The array whose elements you want to join.
Basic Example
Here's a simple example of creating a comma-separated list from a numeric array ?
<?php
$arr = array(100, 200, 300, 400, 500);
echo "Original array: ";
print_r($arr);
echo "\nComma separated list: ";
echo implode(', ', $arr);
?>
Original array: Array
(
[0] => 100
[1] => 200
[2] => 300
[3] => 400
[4] => 500
)
Comma separated list: 100, 200, 300, 400, 500
Handling Whitespace in Array Elements
When array elements contain extra whitespace, you may want to trim them before creating the list ?
<?php
$arr = array(" John ", "Jacob ", " Tom ", " Tim ");
echo "Array with whitespaces:<br>";
foreach($arr as $value) {
echo "Value = '$value'<br>";
}
// Create comma-separated list with trimmed values
$trimmed = array_map('trim', $arr);
echo "\nComma separated list: ";
echo implode(', ', $trimmed);
?>
Array with whitespaces: Value = ' John ' Value = 'Jacob ' Value = ' Tom ' Value = ' Tim ' Comma separated list: John, Jacob, Tom, Tim
Different Separators
You can use any separator, not just commas ?
<?php
$fruits = array("apple", "banana", "orange");
echo "Comma separated: " . implode(', ', $fruits) . "<br>";
echo "Pipe separated: " . implode(' | ', $fruits) . "<br>";
echo "Dash separated: " . implode(' - ', $fruits) . "<br>";
?>
Comma separated: apple, banana, orange Pipe separated: apple | banana | orange Dash separated: apple - banana - orange
Conclusion
The implode() function is the most efficient way to create comma-separated lists from PHP arrays. Combine it with array_map('trim', $array) to handle whitespace issues in your data.
