downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

join> <htmlspecialchars
[edit] Last updated: Fri, 17 May 2013

view this page in

implode

(PHP 4, PHP 5)

implodeJunta elementos de uma matriz em uma string

Descrição

string implode ( string $glue , array $pieces )

Retorna uma string contendo os elementos da matriz na mesma ordem com uma ligação entre cada elemento.

Exemplo #1 implode() exemplo

<?php

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

print 
$comma_separated// lastname,email,phone

?>

Nota:

implode() pode, por razões históricas, aceitar seus parâmetros nas duas ordens. Para consistência com explode(), entretando, ela pode ser menos confusa por usar a ordem documentada dos argumentos.

Nota:

Apartir do PHP 4.3.0, o parametro glue da função implode() é opcional e seu padrão é uma string em branco(''). Este não é o uso preferido de implode(). Nós recomendamos sempre usar dois parametros para compatibilidade com versões anteriores.

Veja também explode(), e split().



join> <htmlspecialchars
[edit] Last updated: Fri, 17 May 2013
 
add a note add a note User Contributed Notes implode - [9 notes]
up
19
houston_roadrunner at yahoo dot com
4 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
2
jento
2 months ago
function implode_r($glue,$arr){
        $ret_str = "";
        foreach($arr as $a){
                $ret_str .= (is_array($a)) ? implode_r($glue,$a) : "," . $a;
        }
        return $ret_str;
}
up
11
php.net {at} nr78 {dot} net
8 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
4
masterandujar
8 months 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)"
?>
up
3
alexey dot klimko at gmail dot com
1 year 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
0
omar dot ajoue at kekanto dot com
2 months 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
-2
Cedric at isoca dot com
10 years ago
Implode with an unset array will made a warning and fail, but is ok with an empty array.
So if you don't trust the content of the array, allways initialize it before :
  $param = array();
  [...]
  echo implode('&', $param);
up
-1
Anonymous
2 months 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
0
Anonymous
29 days ago
/*Defining the associative array to keep the name of
              toppings checked*/   
            $arrayOfMeatToppingsSelected = array();
            $arrayOfVegetablesToppingsSelected = array();

            //Imploding of the names of the toppings checked
            $implodedArrayOfMeatToppingsSelected = implode(', ', $arrayOfMeatToppingsSelected);   
            $implodedArrayOfVegetablesToppingsSelected = implode(', ', $arrayOfVegetablesToppingsSelected);           

        <form action="orderConfirmation.php" method="post">
                    <input type="hidden" name="firstName" value="<?php echo $firstName; ?>" />
                    <input type="hidden" name="lastName" value="<?php echo $lastName; ?>" />
                    <input type="hidden" name="address" value="<?php echo $address; ?>" />
                    <input type="hidden" name="city" value="<?php echo $city; ?>" />
                    <input type="hidden" name="province" value="<?php echo $province; ?>" />
                    <input type="hidden" name="postalCode" value="<?php echo $postalCode; ?>" />
                    <input type="hidden" name="telephone" value="<?php echo $telephone; ?>" />
                    <input type="hidden" name="email" value="<?php echo $email; ?>" />
                    <input type="hidden" name="numberPizza" value="<?php echo $numberPizza; ?>" />
                    <input type="hidden" name="sizePizza" value="<?php echo $sizePizza; ?>" />
                    <input type="hidden" name="crustTypePizza" value="<?php echo $crustTypePizza; ?>" />
                    <input type="hidden" name="toppings" value="<?php echo $checkBoxCount; ?>" />
                    <input type="hidden" name="extrasPizza" value="<?php echo $extrasPrice; ?>" />
                    <input type="hidden" name="price" value="<?php echo $price; ?>" />
                    <input type="hidden" name="priceTax" value="<?php echo $priceTax; ?>" />
                    <input type="hidden" name="finalPrice" value="<?php echo $finalPrice; ?>" />
                    <input type="hidden" name="deletion" value="<?php echo "1"; ?>" />
                    <input type="hidden" name="implodedArrayOfMeatToppingsSelected"
                        value="<?php echo $implodedArrayOfMeatToppingsSelected; ?>" />
                    <input type="hidden" name="implodedArrayOfVegetablesToppingsSelected"
                        value="<?php echo $implodedArrayOfVegetablesToppingsSelected; ?>" />
           
                    <input type="submit" value="Submit" />
                </form>

 
show source | credits | sitemap | contact | advertising | mirror sites