SunshinePHP 2019

implode

(PHP 4, PHP 5, PHP 7)

implodeJoin array elements with a string

Descrierea

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

Join array elements with a glue string.

Notă:

implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

Parametri

glue

Defaults to an empty string.

pieces

The array of strings to implode.

Valorile întoarse

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Exemple

Example #1 implode() example

<?php

$array 
= array('lastname''email''phone');
$comma_separated implode(","$array);

echo 
$comma_separated// lastname,email,phone

// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""

?>

Note

Notă: Această funcție acceptă și date binare.

A se vedea și

add a note add a note

User Contributed Notes 20 notes

up
257
houston_roadrunner at yahoo dot com
9 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
106
omar dot ajoue at kekanto dot com
5 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
11
Felix Rauch
2 years ago
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
up
4
admin at lanlink dot net dot au
1 year ago
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"
?>
up
61
php.net {at} nr78 {dot} net
13 years ago
Also quite handy in INSERT statements:

<?php

  
// array containing data
  
$array = array(
     
"name" => "John",
     
"surname" => "Doe",
     
"email" => "j.doe@intelligence.gov"
  
);

  
// build query...
  
$sql  = "INSERT INTO table";

  
// implode keys of $array...
  
$sql .= " (`".implode("`, `", array_keys($array))."`)";

  
// implode values of $array...
  
$sql .= " VALUES ('".implode("', '", $array)."') ";

  
// execute query...
  
$result = mysql_query($sql) or die(mysql_error());

?>
up
1
jarmo_palomaki at gmx dot de
4 months ago
You can also use array_map to extract fields of objects:

$errors = sqlsrv_errors();
if ($errors != null)
    return implode(' ',array_map($errors, function($e){ return $e['message']; }));
else return "";
up
30
alexey dot klimko at gmail dot com
7 years ago
If you want to implode an array of booleans, you will get a strange result:
<?php
var_dump
(implode('',array(true, true, false, false, true)));
?>

Output:
string(3) "111"

TRUE became "1", FALSE became nothing.
up
24
Anonymous
5 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:
<?php
var_dump
(implode(':', 'xxxxx'));
?>
returns
NULL

This threw me for a little while.
up
18
masterandujar
6 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
8
Anonymous
3 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,,world
print(implode(',', array_filter($ar, function($v){ return $v !== null; }))); // hello,world
?>
up
1
ASchmidt at Anamera dot net
23 days 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:

<?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
up
-1
radoslaw dot paluszak at gmail dot com
2 years ago
A very neat option to limit the number of pieces being imploded is by using array_slice (http://php.net/array_slice):

<?php
$picnames
= array("pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg", "pic5.jpg", "pic6.jpg", "pic7.jpg");
$allpics = implode("|", array_slice($picnames, 0, 5)); 
?>

Hope it helps!
up
-10
Jacques Amar
4 years ago
Safe way to pass as parameters in IN

<?php
$id_nums
= array(1,6,12,18,24);
$p_types = '';
$qs    = array();
foreach (
$id_nums as $id) {
   
$qs[]   = '?';
   
$p_types .= 'i'; // or whatever type
}
$nums_list = implode(',', $qs);
            
$sqlquery = "Select name,email,phone from usertable where user_id IN ($nums_list)";

$stmt = $dbh->stmt_init();
$stmt->prepare($sqlquery);
// later on, instead of bind:
$parms_array = array_merge(array($p_types), $id_nums);
call_user_func_array(array($stmt,'bind_param'), $parms_array );

// $sqlquery becomes "Select name,email,phone from usertable where user_id IN (?,?,?,?,?)"
?>
up
-5
jack dot r dot davis dot jr at gmail dot com
9 months ago
A handy use for implode():

<?php

function tablerow ($array)
{
   
$rv = "<tr><td>" . implode("</td><td>" , $array) . "</td></tr>";
    return(
$rv);
}

function
tablehead($array)
{
   
$rv = "<tr><th>" . implode("</th><th>" , $array) . "</th></tr>";
    return(
$rv);
}

$db = mysqli_connect("localhost","user","password", "dbname");

$sql = "select id, name, city from users";
$query = mysqli_query($db, $sql);

while (
$r  = mysqli_fetch_array($query, MYSQLI_ASSOC))
{
    if (!
$keys)
       
$keys = array_keys($r);
   
$rows[] = tablerow($r);
}

$headers = tablehead($keys);
$rows = implode("", $rows);
echo
"<table>" . $headers . $rows. "</table>";

?>
up
-13
mulahalilovic at yahoo dot com
1 year ago
<?php

//Basic loop into <li>, maybe for some help

$some_string= 'jordan pippen rodman jeckson divac shaq';

$string_to_array= explode(' ',$some_string);

foreach (
$string_to_array as $value):
   
        echo
"<li>";

            echo
$value;

        echo
"</li>";
   

    endforeach;

?>

/*jordan
pippen
rodman
jeckson
divac
shaq
*/
up
-12
erkan karata
1 year ago
Dizi içerisindeki veriyi istenilen yapıştırıcı ile birleştirir.

<?php
echo implode(' ', ['lorem','dolor','sit','amed']); //lorem dolor sit amed
?>
up
-13
Xaib
8 months ago
I using this code..

<?php
$values
= get_field('job_qualification', $post->post_parent, true);
$comma_separated = implode(",", $values);
echo
$comma_separated;
?>

and I am getting errors in error_log file..

[22-Mar-2018 14:12:12 UTC] PHP Warning:  implode(): Invalid arguments passed in /home/********** on line 51
up
-17
theo dot van dot eijndhoven at chello dot nl
1 year ago
implode stops upon encountering NULL

$myArray = ('one', 'two', 'three', null, 'four', 'five');
echo implode(', ', $myArray);

output:
one, two, three
up
-14
veyselkorkmaz44 at gmail dot com
1 year ago
<?php

$dizi
= array('soyadı', 'eposta', 'telefon');
$virgül_ayraçlı = implode(",", $array);

echo
$virgül_ayraçlı; // soyadı,eposta,telefon

?>

BU İŞLEM YANLIŞ!!!!

$array yerine $dizi olması gerekiyordu...yanii.....

<?php

$dizi
= array('soyadı', 'eposta', 'telefon');
$virgül_ayraçlı = implode(",", $dizi);

echo
$virgül_ayraçlı; // soyadı,eposta,telefon

?>
up
-101
cottton at i-stats dot net
4 years ago
in case you want to implode by keys:
<?php
const POSITION_KEY = 0;
const
POSITION_VAL = 2;
const
POSITION_DESC = 1;

$key = 'key';
$val = 'val';
$desc = 'desc';

$arr = array(
   
POSITION_KEY => $key,
   
POSITION_VAL => $val,
   
POSITION_DESC => $desc,
);
echo
kimplode('=',$arr); // key=desc=val
echo '<br>';
echo
krimplode('=',$arr); // val=desc=key

function kimplode($glue,$arr){
   
ksort($arr);
    return
implode($glue,$arr);
}
function
krimplode($glue,$arr){
   
krsort($arr);
    return
implode($glue,$arr);
}
?>
To Top