The implode()
function in PHP is used to join elements of an array into a single string. You can specify a glue (a string used to join the elements).
Syntax
implode(string $separator, array $array): string
Note: $separator
is optional in some PHP versions; however, it’s recommended to always provide it for clarity.
✅ Basic Example
$fruits = ['apple', 'banana', 'mango'];
$result = implode(", ", $fruits);
echo $result; // Output: apple, banana, mango
✅ Using Different Separator
$numbers = [1, 2, 3, 4, 5];
echo implode(" - ", $numbers); // Output: 1 - 2 - 3 - 4 - 5
✅ Without Separator (Empty String)
$letters = ['H', 'E', 'L', 'L', 'O'];
echo implode("", $letters); // Output: HELLO
✅ Using Implode with Associative Array
$data = ['name' => 'John', 'age' => 30];
echo implode(", ", $data); // Output: John, 30
It ignores the keys and just joins the values.
✅ Alternative Syntax (PHP < 7.4)
$colors = ['red', 'green', 'blue'];
echo implode($colors); // Output: redgreenblue (if separator not passed)
Older versions allowed implode(array $array, string $separator)
, but the separator-first version is preferred.
💡 Use Case Example: Converting array for SQL IN clause
$ids = [101, 102, 103];
$sql = "SELECT * FROM users WHERE id IN (" . implode(", ", $ids) . ")";
echo $sql;
// Output: SELECT * FROM users WHERE id IN (101, 102, 103)