implode

(PHP 4, PHP 5)

implodeUnisce gli elementi di una matrice in una stringa

Descrizione

string implode ( string $glue , array $pieces )

Restituisce una stringa contenente tutti gli elementi di una matrice nel medesimo ordine, inserendo il parametro glue tra un elemento e l'altro.

Example #1 Esempio di uso di implode()

<?php

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

echo 
$comma_separated// lastname,email,phone

?>

Nota:

La funzione implode(), per ragioni storiche, può accettare i propri parametri in entrambi gli ordini. Tuttavia per mantenere la consistenza con explode(), ed avere meno confusione, utilizzare i parametri nell'ordine documentato.

Nota:

Dal PHP 4.3.0, il parametro glue di implode() è opzionale e come default utilizza una stringa vuota (''). Questo non è l'utilizzo preferenziale di implode(). Si suggerisce di utilizzare sempre il secondo parametro per compatibilità con le vecchie versioni.

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche explode() e split().

add a note add a note

User Contributed Notes 15 notes

up
209
houston_roadrunner at yahoo dot com
8 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
82
omar dot ajoue at kekanto dot com
4 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
62
php.net {at} nr78 {dot} net
12 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
29
alexey dot klimko at gmail dot com
6 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
23
Anonymous
4 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
2
Felix Rauch
11 months 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
10
masterandujar
5 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
5
Anonymous
2 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
2
radoslaw dot paluszak at gmail dot com
1 year 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
1
mulahalilovic at yahoo dot com
8 months 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
2
Jacques Amar
3 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
0
admin at lanlink dot net dot au
10 days 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
0
erkan karata
1 month 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
-87
cottton at i-stats dot net
3 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);
}
?>
up
-10
theo dot van dot eijndhoven at chello dot nl
5 months ago
implode stops upon encountering NULL

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

output:
one, two, three
To Top