implode

(PHP 4, PHP 5)

implodeОбъединяет элементы массива в строку

Описание

string implode ( string $glue , array $pieces )
string implode ( array $pieces )

Объединяет элементы массива с помощью строки glue.

Замечание:

По историческим причинам, функции implode() можно передавать аргументы в любом порядке, однако для унификации с функцией explode() следует использовать документированный порядок аргументов.

Список параметров

glue

По умолчанию равен пустой строке. Это не является предпочтительным вариантом использования implode(), т.к. glue в таком случае будет вторым параметром, а это значит, что используется нежелательный прототип.

pieces

Массив объединяемых строк.

Возвращаемые значения

Возвращает строку, содержащую строкое представление всех элементов массива в указанном порядке, со строкой glue между каждым элементом.

Список изменений

Версия Описание
4.3.0 Параметр glue стал необязательным

Примеры

Пример #1 Пример использования implode()

<?php

$array 
= array('имя''почта''телефон');
$comma_separated implode(","$array);

echo 
$comma_separated// имя,почта,телефон

// Пустая строка при использовании пустого массива:
var_dump(implode('hello', array())); // string(0) ""

?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • explode() - Разбивает строку с помощью разделителя
  • preg_split() - Разбивает строку по регулярному выражению

Коментарии

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: ''
2009-04-07 14:50:24
http://php5.kiev.ua/manual/ru/function.implode.html
If you want to implode an array of booleans, you will get a strange result:
<?php
var_dump
(implode('',array(truetruefalsefalsetrue)));
?>

Output:
string(3) "111"

TRUE became "1", FALSE became nothing.
2011-06-23 08:04:36
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
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.
2012-09-03 09:15:39
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
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:
<?php
var_dump
(implode(':''xxxxx'));
?>
returns
NULL

This threw me for a little while.
2013-02-26 17:56:31
http://php5.kiev.ua/manual/ru/function.implode.html
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! ;)
2013-03-18 16:21:09
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
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,,world
print(implode(','array_filter($ar, function($v){ return $v !== null; }))); // hello,world
?>
2015-07-20 14:55:18
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
It might be worthwhile noting that the array supplied to implode() can contain objects, provided the objects implement the __toString() method.

Example:
<?php

class 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
2016-09-30 12:39:50
http://php5.kiev.ua/manual/ru/function.implode.html
It is possible for an array to have numeric values, as well as string values. Implode will convert all numeric array elements to strings.

<?php
$test
=implode(["one",2,3,"four",5.67]);
echo 
$test;
//outputs: "one23four5.67"
?>
2017-09-15 07:24:27
http://php5.kiev.ua/manual/ru/function.implode.html
It's not obvious from the samples, if/how associative arrays are handled. The "implode" function acts on the array "values", disregarding any keys:

<?php
declare(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
2018-11-23 23:43:44
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
If you want to use a key inside array:

Example:
$arr=array(
array("id" => 1,"name" => "Test1"),
array("id" => 2,"name" => "Test2"),
);

echo implode_key(",",$arr, "name");
OUTPUT: Test1, Test2

function implode_key($glue, $arr, $key){
    $arr2=array();
    foreach($arr as $f){
        if(!isset($f[$key])) continue;
        $arr2[]=$f[$key];
    }
    return implode($glue, $arr2);
}
2020-04-02 19:28:58
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
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.

<?php
function mapped_implode($glue$array$symbol '=') {
    return 
implode($gluearray_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',
   
=> 'Foo',
];

echo 
mapped_implode(', '$arr' is ');

// output: x is 5, y is 7, z is 99, hello is World, 7 is Foo

?>
2020-04-24 20:43:39
http://php5.kiev.ua/manual/ru/function.implode.html
<?php
 
Join pieces with a string recursively.
 * 
 * @
param mixed $glue String between pairs(glue) or an array pair's glue and key/value glue or $pieces.
 * @param iterable $pieces Pieces to implode (optional).
 * @return string Joined string
 */
function double_implode($glue, iterable $pieces = null): string
{
    $glue2 = null;
    if ($pieces === null) {
        $pieces = $glue;
        $glue = '';
    } elseif (is_array($glue)) {
        list($glue, $glue2) = $glue;
    }
   
    $result = [];
    foreach ($pieces as $key => $value) {
        $result[] = $glue2 === null ? $value : $key . $glue2 . $value;
    }
    return implode($glue, $result);
}
?>
Examples:
<?php
$array = ['
a' => 1, 'b' => 2];
$str =  implode($array);
$str =  implode('
', $array);
$str =  implode(['" ', '="'], $array);

$iterator = new ArrayIterator($array);
$str =  implode($iterator);
$str =  implode('
', $iterator);
$str =  implode(['" ', '="'], $iterator);
?>
2020-08-28 20:32:01
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
Sometimes it's necessary to add a string not just between the items, but before or after too, and proper handling of zero items is also needed.
In this case, simply prepending/appending the separator next to implode() is not enough, so I made this little helper function.

<?php

function wrap_implode$array$before ''$after ''$separator '' ){
  if( ! 
$array )  return '';
  return 
$before implode("{$after}{$separator}{$before}"$array ) . $after;
}

echo 
wrap_implode(['path','to','file.php'], '/');
// "/path/to/file.php"

$pattern '#'wrap_implode([4,2,2], '\d{''}''[-.]') .'#';
echo 
$pattern"\n"// #\d{4}[-.]\d{2}[-.]\d{2}#
echo preg_replace$pattern'[REDACTED]''The UFO appeared between 2012-12-24 and 2013.01.06 every night.');
// 'The UFO appeared between [REDACTED] and [REDACTED] every night.

echo wrap_implode(['line','by','line'], '<b>''</b>''<br>  ');
// <b>line</b><br>  <b>by</b><br>  <b>line</b>

echo wrap_implode( ['<a href="">Menu Item 1</a>''<a href="">Menu Item 2</a>',],
 
"<li>""</li>\n",
 
"<li> | </li>\n",
);
/*
<li><a href="">Link1</a></li>
<li> | </li>
<li><a href="">Link2</a></li>
*/

?>
2021-04-10 01:30:24
http://php5.kiev.ua/manual/ru/function.implode.html
There is no mention of behavior on a empty array, so I tried it and here's the result:

<?php
$ar 
= array();
$result implode(','$ar);  // Comma arbitrarily applied as the separator
$is_result_empty = empty($result);
?>

$result: 
$is_result_empty: 1

In other words, an empty string is the result.
2021-11-13 17:36:49
http://php5.kiev.ua/manual/ru/function.implode.html

    Поддержать сайт на родительском проекте КГБ