Strings7 min readExamples run on PHP 8.5.10

implode()

Learn how PHP 8.4 implode() joins array values into one string, how it converts non-string elements, and which mistakes to avoid.

Signature

implode(string $separator, array $array): string
implode(array $array): string
Available since PHP 4.0 · removed in 8.0.07.48.08.18.28.38.48.5All versions →

Purpose

implode() takes an array and produces one string. The values appear in the array's iteration order, with a separator string placed between neighbouring values. It is the usual tool for building comma-separated lists, space-separated CSS class names, breadcrumb trails or a run of SQL placeholders. It is the opposite of explode(), which splits a string into pieces.

Signature

The second form is an alternative signature and is not supported with named arguments. The old form that put the separator after the array was deprecated in PHP 7.4.0 and has not been supported since PHP 8.0.0, so the separator always comes first.

Parameters and defaults

  • separator: the text inserted between elements. It is optional and defaults to an empty string. It may be longer than one character, and it is not interpreted as a pattern.
  • array: the array whose values are joined. Keys are ignored; only values and their order matter.

When you pass only one argument, it must be the array: implode($items) is the same as joining with an empty separator.

Return value and failure cases

The function returns a string. An empty array gives an empty string, whatever the separator is. An array with one element gives that element converted to a string, with no separator added.

Passing something that is not an array in the array position, such as a plain string, raises a TypeError. Elements that cannot be converted to a string cause trouble too: an object without __toString() throws an Error, and a nested array is converted to the text Array along with a warning. The manual notes that the function is binary-safe, so separators and elements may contain any bytes.

Example 1: the basic forms

The first example shows a separator, the single-argument form and an empty array.

Example
<?php
$parts = ['lastname', 'email', 'phone'];
echo json_encode([
    implode(',', $parts),
    implode(['a', 'b', 'c']),
    implode('hello', []),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
["lastname,email,phone","abc",""]

The separator appears only between elements, never at the start or the end. The empty array yields an empty string even though the separator is hello.

Example 2: conversion and keys

Elements are converted to strings with the normal conversion rules. Integers and floats become their decimal text, true becomes 1, and false and null become empty strings. Objects work when their class defines __toString(). Keys never appear in the result.

Example
<?php
final class Tag
{
    public function __construct(private string $name) {}

    public function __toString(): string
    {
        return '#' . $this->name;
    }
}

echo json_encode([
    implode('|', [1, 2.5, true, false, null, 'x']),
    implode(',', ['b' => 'x', 'a' => 'y']),
    implode(', ', [new Tag('php'), new Tag('web')]),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
["1|2.5|1|||x","x,y","#php, #web"]

Notice the three adjacent pipes in the first result. They come from false and null, which both contribute nothing but still occupy a position, so the separators around them remain.

Example 3: practical joins

A common pattern is to clean an array before joining it. Here array_filter() removes null and empty strings so that no stray spaces are left in a class list. The second value builds placeholders for a query that would use three parameters.

Example
<?php
$classes = ['btn', '', 'btn-primary', null, 'active'];
$visible = array_filter($classes, fn($value) => $value !== null && $value !== '');
$placeholders = implode(', ', array_fill(0, 3, '?'));

echo json_encode([
    'classes' => implode(' ', $visible),
    'placeholders' => $placeholders,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
{"classes":"btn btn-primary active","placeholders":"?, ?, ?"}

array_filter() keeps the original keys, which is harmless here because implode() ignores keys.

Edge cases

  • Empty entries still produce separators. Joining ['a', '', 'b'] with a comma gives a,,b, so filter first if that is not what you want.
  • The default filter of array_filter() also removes 0 and "0", which are falsy. Use an explicit callback when those are valid values.
  • Floats use PHP's string conversion, so do not rely on implode() for locale-specific number formatting.
  • Nested arrays are not flattened. Flatten them yourself or join the inner arrays first.

Common mistakes

  1. Using the pre-8.0 argument order, implode($array, ','). This is no longer supported; write implode(',', $array).
  2. Passing a string where an array is expected, for example the result of a previous join. This raises a TypeError.
  3. Expecting associative keys to be included. If you need key=value text, map the pairs first, or use http_build_query() for URL query strings.
  4. Forgetting that null and false vanish silently and leave doubled separators.
  5. Trying to join objects that do not implement __toString().
  • explode() splits a string by a separator string and is the inverse operation.
  • preg_split() splits by a regular expression when a fixed separator is not enough.
  • http_build_query() builds a URL-encoded query string from an array.
  • array_filter() and array_map() are often used to prepare the array before joining.

Recap

Call implode($separator, $array) with the separator first. The result is a string containing the values in order, with the separator only between them. Keys are ignored, scalars are converted to strings, null and false become empty text, and an empty array produces an empty string. Clean or flatten the data first when the output must not contain empty slots.

Tested examples

Basic forms: separator, no separator and an empty array
<?php
$parts = ['lastname', 'email', 'phone'];
echo json_encode([
    implode(',', $parts),
    implode(['a', 'b', 'c']),
    implode('hello', []),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
["lastname,email,phone","abc",""]
String conversion, ignored keys and Stringable objects
<?php
final class Tag
{
    public function __construct(private string $name) {}

    public function __toString(): string
    {
        return '#' . $this->name;
    }
}

echo json_encode([
    implode('|', [1, 2.5, true, false, null, 'x']),
    implode(',', ['b' => 'x', 'a' => 'y']),
    implode(', ', [new Tag('php'), new Tag('web')]),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
["1|2.5|1|||x","x,y","#php, #web"]
Practical joins: class list and query placeholders
<?php
$classes = ['btn', '', 'btn-primary', null, 'active'];
$visible = array_filter($classes, fn($value) => $value !== null && $value !== '');
$placeholders = implode(', ', array_fill(0, 3, '?'));

echo json_encode([
    'classes' => implode(' ', $visible),
    'placeholders' => $placeholders,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
Output
{"classes":"btn btn-primary active","placeholders":"?, ?, ?"}