What does implode() do?
implode() concatenates the values of an array, placing $separator between each pair. Keys are ignored. join() is an exact alias.
Syntax
implode(string $separator, array $array): string
implode(array $array): string
Parameters
$separator- String placed between elements. Optional; defaults to an empty string.$array- The array whose values are joined. Values are converted to strings (truebecomes "1",falseandnullbecome "").
Return value
A string containing all array values separated by $separator. An empty array returns an empty string.
implode() examples
Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.
1. Join with different separators
<?php
$fruits = ["apple", "banana", "cherry"];
echo implode(", ", $fruits) . "\n";
echo implode(" | ", $fruits) . "\n";
echo implode($fruits) . "\n";
Output:
apple, banana, cherry apple | banana | cherry applebananacherry
2. Associative arrays: values, keys and key=value pairs
<?php
$user = ["name" => "Alice", "role" => "admin", "active" => true];
echo implode(", ", $user) . "\n";
echo implode(", ", array_keys($user)) . "\n";
$pairs = [];
foreach ($user as $key => $value) {
$pairs[] = "$key=$value";
}
echo implode("&", $pairs) . "\n";
Output:
Alice, admin, 1 name, role, active name=Alice&role=admin&active=1
3. Build SQL placeholders and an HTML list
<?php
$ids = [4, 8, 15];
$placeholders = implode(", ", array_fill(0, count($ids), "?"));
echo "SELECT * FROM users WHERE id IN ($placeholders)\n";
$items = ["Home", "About", "Contact"];
echo "<ul><li>" . implode("</li><li>", $items) . "</li></ul>\n";
Output:
SELECT * FROM users WHERE id IN (?, ?, ?) <ul><li>Home</li><li>About</li><li>Contact</li></ul>
Common mistakes and gotchas
- Argument order: the legacy order
implode($array, $separator)was removed in PHP 8.0 and now throws aTypeError. Always pass the separator first. - Nested arrays: inner arrays become the string "Array" with an "Array to string conversion" warning. Flatten them first or use
json_encode(). - Booleans:
truebecomes "1" andfalsebecomes "", which can surprise you in output. - Query strings: for URLs prefer
http_build_query($array), which also URL-encodes the values.