PHP implode() Function
PHP implode() joins all the elements of an array into one string.
It is a built-in function. You give it a separator (also called glue) and an array, and it returns a single string with the separator placed between every value. The implode() function works opposite of explode(), which breaks a string into array.
Syntax
implode(string $separator, array $array): string
There is also a second form where you pass only the array. In this case PHP joins the values without any separator.
implode(array $array): string
join() is an alias of implode(). Both work same, but implode() is more commonly used.
Parameters
The array is required. The separator is optional.
| Parameter | Description |
|---|---|
| separator | Optional. The string placed between array values. Default is an empty string |
| array | Required. The array whose values you want to join |
Return value: implode() returns a string. For an empty array it returns an empty string.
Examples
Example #1: Join names with a space
Here we have an array of names. We pass a space as separator, so all the names come out in one string.
<?php
// Array of names
$names = ["Robin", "Jenny", "Rocky"];
// Join array values using space
$result = implode(" ", $names);
echo $result;
?>
Output:
Robin Jenny Rocky
Example #2: Join values with comma and space
Comma with a space is the most common separator. Use it when you want to show array values as single line list.
<?php
$fruits = ["Apple", "Banana", "Orange", "Mango"];
echo implode(", ", $fruits);
?>
Output:
Apple, Banana, Orange, Mango
Example #3: Join without a separator
If you pass only the array, the values are joined directly one after another.
<?php
$letters = ["P", "H", "P"];
echo implode($letters);
?>
Output:
PHP
Example #4: Associative array
For an associative array, implode() joins the values only. Keys are ignored. If you need the keys, use array_keys() first.
<?php
$user = ["name" => "Robin", "city" => "Delhi", "age" => 25];
// Join values
echo implode(" | ", $user) . "<br>";
// Join keys
echo implode(" | ", array_keys($user));
?>
Output:
Robin | Delhi | 25
name | city | age
Common mistakes
- Passing a string instead of an array. In PHP 8 this throws a TypeError.
- Using a nested array. implode() cannot join an array inside another array. You will get the word “Array” and a warning “Array to string conversion”.
- Boolean and null values.
truebecomes “1”, whilefalseandnullbecome an empty string.
Summary
- implode() joins array values into a string.
- Separator goes first and array goes second.
- join() is an alias of implode().
- It uses values only, keys are ignored.
- It is the opposite of explode().
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |