implode

(PHP 4, PHP 5, PHP 7, PHP 8)

implodeAglutina elementos de um array com uma string

Descrição

implode(string $separator, array $array): string

Assinatura alternativa (não suportada com argumentos nomeados):

implode(array $array): string

Assinatura legada (descontinuada a partir do PHP 7.4.0, removida a partir do PHP 8.0.0):

implode(array $array, string $separator): string

Combina elementos de um array com um string de separação definida por separator.

Parâmetros

separator

Opcional. O padrão é uma string vazia.

array

O array de strings a implodir.

Valor Retornado

Retorna uma string contendo um representação de todos os elementos do array na mesma ordem, com a string separadora entre eles.

Registro de Alterações

Versão Descrição
8.0.0 Passar separator depois de array não é mais suportado.
7.4.0 Passar separator depois de array (isto é, usando a assinatura legada) foi descontinuado.

Exemplos

Exemplo #1 Exemplo de implode()

<?php

$array
= ['sobrenome', 'email', 'telefone'];
var_dump(implode(",", $array)); // string(24) "sobrenome,email,telefone"

// String vazia ao usar um array vazio:
var_dump(implode('olá', [])); // string(0) ""

// O separador é opcional:
var_dump(implode(['a', 'b', 'c'])); // string(3) "abc"

?>

Notas

Nota: Esta função é compatível com dados binários.

Veja Também

adicione uma nota

Notas Enviadas por Usuários (em inglês) 9 notes

up
364
houston_roadrunner at yahoo dot com
16 years ago
it should be noted that an array with one or no elements works fine. for example:<?php    $a1 = array("1","2","3");    $a2 = array("a");    $a3 = array();        echo "a1 is: '".implode("','",$a1)."'<br>";    echo "a2 is: '".implode("','",$a2)."'<br>";    echo "a3 is: '".implode("','",$a3)."'<br>";?>will produce:===========a1 is: '1','2','3'a2 is: 'a'a3 is: ''
up
98
ASchmidt at Anamera dot net
6 years ago
It's not obvious from the samples, if/how associative arrays are handled. The "implode" function acts on the array "values", disregarding any keys:<?phpdeclare(strict_types=1);$a = array( 'one','two','three' );$b = array( '1st' => 'four', 'five', '3rd' => 'six' );echo implode( ',', $a ),'/', implode( ',', $b );?>outputs:one,two,three/four,five,six
up
104
omar dot ajoue at kekanto dot com
12 years ago
Can also be used for building tags or complex lists, like the following:<?php$elements = array('a', 'b', 'c');echo "<ul><li>" . implode("</li><li>", $elements) . "</li></ul>";?>This is just an example, you can create a lot more just finding the right glue! ;)
up
27
Felix Rauch
8 years ago
It might be worthwhile noting that the array supplied to implode() can contain objects, provided the objects implement the __toString() method.Example:<?phpclass Foo{    protected $title;    public function __construct($title)    {        $this->title = $title;    }    public function __toString()    {        return $this->title;    }}$array = [    new Foo('foo'),    new Foo('bar'),    new Foo('qux')];echo implode('; ', $array);?>will output:foo; bar; qux
up
47
alexey dot klimko at gmail dot com
14 years ago
If you want to implode an array of booleans, you will get a strange result:<?phpvar_dump(implode('',array(true, true, false, false, true)));?>Output:string(3) "111"TRUE became "1", FALSE became nothing.
up
9
Honk der Hase
5 years ago
If you want to implode an array as key-value pairs, this method comes in handy. The third parameter is the symbol to be used between key and value.<?phpfunction mapped_implode($glue, $array, $symbol = '=') {    return implode($glue, array_map(            function($k, $v) use($symbol) {                 return $k . $symbol . $v;            },             array_keys($array),             array_values($array)            )        );}$arr = [    'x'=> 5,     'y'=> 7,     'z'=> 99,    'hello' => 'World',    7 => 'Foo',];echo mapped_implode(', ', $arr, ' is ');// output: x is 5, y is 7, z is 99, hello is World, 7 is Foo?>
up
20
Anonymous
12 years ago
It may be worth noting that if you accidentally call implode on a string rather than an array, you do NOT get your string back, you get NULL:<?phpvar_dump(implode(':', 'xxxxx'));?>returnsNULLThis threw me for a little while.
up
13
masterandujar
12 years ago
Even handier if you use the following:

<?php
$id_nums = array(1,6,12,18,24);

$id_nums = implode(", ", $id_nums);
                
$sqlquery = "Select name,email,phone from usertable where user_id IN ($id_nums)";

// $sqlquery becomes "Select name,email,phone from usertable where user_id IN (1,6,12,18,24)"
?>

Be sure to escape/sanitize/use prepared statements if you get the ids from users.
up
7
Anonymous
10 years ago
null values are imploded too. You can use array_filter() to sort out null values.<?php$ar = array("hello", null, "world");print(implode(',', $ar)); // hello,,worldprint(implode(',', array_filter($ar, function($v){ return $v !== null; }))); // hello,world?>
To Top