★ wanayoo — archive 1999 http://fr.php.net/manual/it/function.implode.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<htmlspecialcharsjoin>
view the version of this page
Last updated: Sun, 21 Nov 2004

implode

(PHP 3, PHP 4 , PHP 5)

implode -- Join array elements with a string

Description

string implode ( string glue, array pieces)

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

Esempio 1. implode() example

<?php

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

echo
$comma_separated; // lastname,email,phone

?>

Nota: 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.

Nota: As of PHP 4.3.0, the glue parameter of implode() is optional and defaults to the empty string(''). This is not the preferred usage of implode(). We recommend to always use two parameters for compatibility with older versions.

See also explode(), and split().



add a note add a note User Contributed Notes
implode
phpWalter at torres dot ws
14-Sep-2004 08:45
Chris Ross (17-Aug-2004 11:18) gave us a great function 'implode_assoc'.

But it didn't handle multi-level array.

I know, a few others here added this "feature", but...

I've modified Chirs' function to be recursive.

Hope it helps someone.

/**
  * Method to recursivly implode a multi-dimensional array
  * Orginal: Chris Ross - 17-Aug-2004
  * Modified: Walter Torres - 09-14-2004
  **/
function implode_assoc_r($inner_glue = "=", $outer_glue = "\n", $array = null, $keepOuterKey = false)
{
   $output = array();

   foreach( $array as $key => $item )
       if ( is_array ($item) )
       {
           if ( $keepOuterKey )
               $output[] = $key;

           // This is value is an array, go and do it again!
           $output[] = implode_assoc_r ($inner_glue, $outer_glue, $item, $keepOuterKey);
       }
       else
           $output[] = $key . $inner_glue . $item;

   return implode($outer_glue, $output);
}
Chris Ross
17-Aug-2004 08:18
I took static's implode_with_keys, and converted into something I considered a little more programatically useful.  I would argue that this sort of functionality should maybe be added to PHP.

<?php
/* This isn't really DB function, but it's general...  This will */
/* act like the PHP implode() function, but for assoc. arrays... */
function implode_assoc($inner_glue, $outer_glue, $array) {
      
$output = array();
       foreach(
$array as $key => $item )
              
$output[] = $key . $inner_glue . $item;

       return
implode($outer_glue, $output);
}
?>

  It's the same as static's, really, but allows you to join the keys to the values with any arbitrary string, rather than hard-coding a '='.
john
26-Apr-2004 11:15
hi,
to prevent implode from putting the zero at the end, I use ksort().

example:

$val[1]="one";
$val[2]="two";
$val[0]="zero";
ksort($val);
echo implode(":",$val);
//will return "zero:one:two"
chris at hitcatcher dot com
28-Oct-2003 10:50
I found it neccesary to create a function that joins the contents of a single dimension from a 2-d array. Here's the code in case anyone else should need to do the same:

<?php
function join_2d($glue, $pieces, $dimension = 0){
  
//joins the values of a single dimension in a 2-d array
  
$rtn = array();
   foreach(
$piece as $key => $value){
       if(isset(
$value[$dimension])){
          
$rtn[] = $value[$dimension];
       }
   }
   return
join($glue, $rtn);
}
?>

The dimension argument can be a positive integer or a named index. Here is an example:

<?php
$testarray
= array(array(1 => 'a', 'three' => 1),
                         array(
1 => 'b', 'three' => 2),
                         array(
1 => 'c', 'three' => 3),
                         array(
1 => 'd', 'three' => 4),
                         array(
1 => 'e', 'three' => 5));

print
"<pre>"; print_r($testarray); print "</pre>";
print
join_2d(", ", $testarray, 1) . "<br>";
print
join_2d(", ", $testarray, 'three') . "<br>";
?>
dan at danposluns dot com
23-Aug-2003 08:04
*** MULTI-DIMENSIONAL ARRAY IMPLODE ***

First of all, it should be noted that the function in the previous note is not technically correct, as it glues the outside of the first piece. This is the problem faced by any function that wants to construct a set out of an array without the overhead of handling the boundary indexes. It also doesn't preserve the dimensional architecture.

Use this function when you want to call implode() on a multi-dimensional array and want the resulting string to preserve the architecture of the different dimensions. For example:

array ( 5, array (2, 4, 6), array (3, 6, 9, array (12)))

would be reduced to:

[ 5, [ 2, 4, 6 ], [ 3, 6, 9, [ 12 ] ] ]

Note that this does not preserve key values. If you need those, you are probably better off using serialize() and then replacing the tokens with your own symbols using the string functions.

Anyway, here is the code:

function mdImpode($x, $y)
{
   $a = (is_array($x)) ? '[ ' . array_reduce($x, 'mdImplode') . ' ]' : $x;
   $b = (is_array($y)) ? '[ ' . array_reduce($y, 'mdImplode') . ' ]' : $y;
   return $a . ', ' . $b;
}

Then to call it, use:

$result = '[ ' . array_reduce($pieces, 'mdImplode') . ' ]';

Note that you have to make manual changes if you want different glue or set symbols. There may be a more elegant solution, but this should be a good compromise between efficiency and simplicity (the manual says that array_reduce is iterative, so this should be pretty speedy).
gregrahkin
19-Jun-2003 07:10
This function will implode a multi-dimension array

function implode_r ($glue, $pieces){
 $out = "";
 foreach ($pieces as $piece)
  if (is_array ($piece)) $out .= implode_r ($glue, $piece); // recurse
  else                  $out .= $glue.$piece;
 
 return $out;
 }
james at globalmegacorp dot org
31-May-2003 04:13
As a followup to the implode_with_keys function posted by 'static', here's a corresponding explode_with_keys function I wrote:

function explode_with_keys($seperator, $string)
{
       $output=array();
       $array=explode($seperator, $string);
       foreach ($array as $value) {
               $row=explode("=",$value);
               $output[$row[0]]=$row[1];
       }
       return $output;
}
ulderico at maber dot com dot br
07-Oct-2002 07:39
'Implode' does not implodes recursively... It might quite useful implode recursively when you get a many Arrays values with keys that replaces themselves as:

http://server/file.php?arg[1]=123&arg[2]=312&arg[3]=543&arg[2]=abc

If you build this URL progressively it would a great a idea that the newest value indeed took the place of any older ones, thus:

http://server/file.php?arg[1]=123&arg[3]=543&arg[2]=abc

would be a better option;

If one uses $_SERVER['REQUEST_URI'], this sanitation would not happen, the URL string would be greater and greater everytime.

With implode_r (see below) it becomes easier to build a "sanitised" URL, the one that less likely will overflow the browser.

$URL = $_SERVER['PHP_SELF'];
$tmp = implode_r("&", $_REQUEST); /* So as to allow to get ANY VALUE (G/P) from the Browser... */
$URL .= "?".$tmp;

/* implode_r */
function implode_r($glue, $array, $array_name = NULL){
while(list($key,$value) = @each($array))
if(is_array($value))
                       $return[] = implode_r($glue, $value, (string) $key);
               else
                       if($array_name != NULL)
                               $return[] = $array_name."[".(string) $key."]=".$value;
                       else
                               $return[] = $key."=".$value;
                              
       return(implode($glue, $return));
}
sorry I couldn't format the code.
Cedric at isoca dot com
11-Jul-2002 07:39
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);
static
14-May-2002 09:43
The one thing missing with this function is a way to add the keys. So I wrote this little function:

function implode_with_keys($glue, $array) {
       $output = array();
       foreach( $array as $key => $item )
               $output[] = $key . "=" . $item;

       return implode($glue, $output);
}
php at woodenpickle dot com
15-Mar-2002 07:55
Hey, I found a good use for implode() today. It came from a need to have a <select name=state multiple> box on the page that a person could select multiple states from and send those to a >SELECT * FROM customers WHERE state='$state'; query. But they need to be able to send just one state also. Well, I changes the html select box to say <select name=state[] multiple>. This turns $state into an array as you may know. I then, later on in the script, did this:

$count = count( $state );
if( $count > 1 ) {
     $states = implode( "'.'", $state );
     $result = $database->query( "SELECT * FROM currentOrders WHERE date>=$from AND date <=$to AND state IN ('$states')" );
}

//This takes care of multiple states, but if the user sent only one state, I catch it here:

foreach( $state as $value );
if( $value )
     $result = $database->query( "SELECT * FROM currentOrders WHERE date>=$from AND date<=$to AND state='$value'" );
else //This one will catch the ALL states option if they choose that.
     $result = $database->query( "SELECT * FROM currentOrders WHERE date>=$from AND date<=$to" );

Anyway, I thought I'd post this up here in case it might help someone. Or maybe someone could figure out a better way and enlighten us all.. Have fun.. Bob

<htmlspecialcharsjoin>
 Last updated: Sun, 21 Nov 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Fri Nov 26 05:15:47 2004 CET