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() - Разбивает строку по регулярному выражению

Коментарии

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
2002-03-15 00:55:17
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
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);
}
2002-05-14 03:43:18
http://php5.kiev.ua/manual/ru/function.implode.html
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);
2002-07-11 13:39:14
http://php5.kiev.ua/manual/ru/function.implode.html
'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.
2002-10-07 13:39:39
http://php5.kiev.ua/manual/ru/function.implode.html
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;
}
2003-05-30 22:13:10
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
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;
 }
2003-06-19 13:10:29
http://php5.kiev.ua/manual/ru/function.implode.html
*** 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).
2003-08-23 14:04:11
http://php5.kiev.ua/manual/ru/function.implode.html
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(=> 'a''three' => 1),
                          array(
=> 'b''three' => 2),
                          array(
=> 'c''three' => 3),
                          array(
=> 'd''three' => 4),
                          array(
=> 'e''three' => 5));

print 
"<pre>"print_r($testarray); print "</pre>";
print 
join_2d(", "$testarray1) . "<br>";
print 
join_2d(", "$testarray'three') . "<br>";
?>
2003-10-28 03:50:12
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
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"
2004-04-26 17:15:51
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
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 '='.
2004-08-17 14:18:02
http://php5.kiev.ua/manual/ru/function.implode.html
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);
}
2004-09-14 14:45:20
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
A handy use of implode in a MySQL query

<?php 
$id_nums 
= array(1,6,12,18,24);

$id_nums implode(" OR user_id="$id_nums);
                 
$sqlquery "Select name,email,phone from usertable where user_id=$id_nums";

// $sqlquery becomes "Select name,email,phone from usertable where user_id=1 OR user_id=6 OR user_id=12 OR user_id=18 OR user_id=24"
?>
2005-03-03 10:29:09
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)"
?>
2005-03-03 11:47:25
http://php5.kiev.ua/manual/ru/function.implode.html
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());

?>
2005-03-30 09:50:32
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
Here is another varriation on the below code. This is useful if you are trying to store data as a string to be returned to an array later.  It allows unlimited nested arrays to be both stored and extracted, but does not print out as pretty.

function implode_assoc_r2($inner_glue = "=", $outer_glue = "\n", $recusion_level = 0, $array = null)
{
   $output = array();

   foreach( $array as $key => $item )
       if ( is_array ($item) )
       {
           // This is value is an array, go and do it again!
           $level = $recusion_level + 1;
           $output[] = $key . $inner_glue . $recusion_level . $inner_glue . implode_assoc_r ($inner_glue, $outer_glue, $level, $item, $keepOuterKey);
       }
       else
           $output[] = $key . $inner_glue . $recusion_level . $inner_glue . $item;

   return implode($outer_glue . $recusion_level . $outer_glue, $output);
}

function explode_assoc_r2($inner_glue = "=", $outer_glue = "\n", $recusion_level = 0, $string = null)
{
       $output=array();
       $array=explode($outer_glue.$recusion_level.$outer_glue, $string);
       
       foreach ($array as $value)
       {
               $row=explode($inner_glue.$recusion_level.$inner_glue,$value);
               $output[$row[0]]=$row[1];
               $level = $recusion_level + 1;
               if(strpos($output[$row[0]],$inner_glue.$level.$inner_glue))
                       $output[$row[0]] = explode_with_keys_a($inner_glue,$outer_glue,$level,$output[$row[0]]);
       }   
       

       return $output;
}
2005-04-01 21:07:43
http://php5.kiev.ua/manual/ru/function.implode.html
I made this function to create an english-readable list from an array.

<?php
function english_list($array$oxfordcomma=1) {
 
$count count($array)-1;
 
$last $array[$count];
  unset(
$array[$count]);
 
$str join(", "$array);
  if (
$oxfordcomma) {
   
$str .= ",";
  }
 
$str .= " and $last";
 
  return 
$str;
}
?>

The optional parameter "oxfordcomma" indicates whether or not to use the Oxford comma (a comma before the "and").

Example:

<?php
print english_list(array("foo""bar""foobar""barfoo"));
?>
Would produce:

foo, bar, foobar, and barfoo
2005-04-14 11:36:45
http://php5.kiev.ua/manual/ru/function.implode.html
/**
     * Like implode but with keys
     *
     * @param string[optional] $glue
     * @param array $pieces
     * @param string[optional] $hifen
     * @return string
     */
    function implode_with_key($glue = null, $pieces, $hifen = ',') {
        $return = null;
        foreach ($pieces as $tk => $tv) $return .= $glue.$tk.$hifen.$tv;
        return substr($return,1);
    }
2005-04-27 09:06:13
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
Similar to a previous note, but this works for any length array, plus also works for arrays with key strings instead of integer keys! I know it's not strictly an implode() example, but it concerns what you might be considering using implode() to help you to do achieve...

<?php
// Return array as a comma separated list; final two elements separated
// by 'and' with an optional "Oxford" comma preceding the 'and'.
function english_list($array$oxfordComma=0)
{
 
$optionalComma = ( $oxfordComma ) ? "," "";
 
$str "";
 
$size count$array );
 
$i 0;
  foreach ( 
$array as $item ) {
   
$str .= $item;
   
$i++;
    if ( 
$i $size 1$str .= ", ";
    elseif ( 
$i == $size 1$str .= $optionalComma." and ";
  }
  return 
$str;
}

// test the comma separated list function
echo english_list( array(), )."<br>";
echo 
english_list( array("foo"), )."<br>";
echo 
english_list( array("foo""bar"), )."<br>";
echo 
english_list( array("a" => "foo""b" => "bar""c" => "foobar"), )."<br>";
echo 
english_list( array("foo""bar""foobar""barfoo"), )."<br>";
?>
2005-04-28 13:19:21
http://php5.kiev.ua/manual/ru/function.implode.html
/* 
  english_list()
This one works with anything, since the array is passed by reference, modifying it in the function via pop has no effect on the array outside the function. But it can't be done on one line, because the array_pop() must occur before the join().
*/

function english_list($array, $oxfordComma=0)
{
  $last = array_pop($array);
  return join(", ", $array) . ($oxfordComma ? "," : "") . " and " . $last;
}
2005-04-28 16:54:57
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
It's always dangerous to give sweeping statements like "this will always work!". Your solution is much more elegant than mine, but perhaps it's a little too elegant for its own good! Try giving it an array with zero or one elements in it for example. You could say that folks shouldn't call it in that case, but you know folks... they like pushing the boundaries. :-)

Perhaps you meant to say that the array can be altered inside the function because it is passed "by value" rather than "by reference", or is that just a mixture of terminology from my C++ upbringing? Passing by reference would imply that you could alter the array inside the function and have that alter its value outside. Passing by value implies that any changes inside the function affect the local function copy only. In PHP, the latter is clearly the case, unless a variable is explicitly declared as global.

OK, that's my 2c.
2005-04-28 20:27:56
http://php5.kiev.ua/manual/ru/function.implode.html
Correction: I meant "passed by value", not "pass by reference". My mistake. Passing by reference would speed up any of these functions by avoiding the copy necessary for "by value.

Other solutions have problems with non-arrays as well. But it demonstrates that there are many ways to solve this problem. Adding checks for non-arrays and short arrays makes the solution less elegant, but safer. Other solutions should have included similar protections.

function english_list($array, $oxfordComma=0)
{
  if (!is_array($array)) return $array;
  if (count($array) <= 1) return join(", ", $array);
  $last = array_pop($array);
  return join(", ", $array) . ($oxfordComma ? "," : "") . " and " . $last;
}
2005-04-29 10:20:52
http://php5.kiev.ua/manual/ru/function.implode.html
Here is another variation on Chris' function. I added a $skip_empty parameter. if it's set to TRUE the result string will not contain keys whose values are empty. Great for building query_strings. If the parameter is not given it behaves like the original function:

$a='1';
$b='';
$c='3';

INPUT: implode_assoc('=','&',array('a'=>$a,'b'=>$b,'c'=>$c),true);
OUTPUT: a=1&c=3

INPUT: implode_assoc('=','&',array('a'=>$a,'b'=>$b,'c'=>$c));
OUTPUT: a=1&b=&c=3

function implode_assoc($inner_glue,$outer_glue,$array,$skip_empty=false){
 $output=array();
 foreach($array as $key=>$item)
  if(!$skip_empty || $item){$output[]=$key.$inner_glue.$item;}
 return implode($outer_glue,$output);
}
2005-05-16 04:29:28
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
in case of value $item==0 but is set is necessary use function isset()

function implode_assoc($inner_glue,$outer_glue,$array,$skip_empty=false){
 $output=array();
 foreach($array as $key=>$item)
  if(!$skip_empty || isset($item)){$output[]=$key.$inner_glue.$item;}
 return implode($outer_glue,$output);
}
2005-05-31 08:42:03
http://php5.kiev.ua/manual/ru/function.implode.html
The function below recursively outputs an array in a format condusive to parsing it in php or another scripting language.  It does NOT output the name of the original array, for that see note 1.  It handles all the cases I could think of elegantly.  Comments and criticisms are welcome.

For an array constructed with:

$arr = array("foo" => array('bar' => array(0 => "value 0", 1 => "value 1")), "foo two" => array(0 => array("bar" => "value2")));

The line below:

echo implode_parseable("=", ";<br>$", $arr, "$", ";");

Will produce:

$foo["bar"][0]="value 0";
$foo["bar"][1]="value 1";
$foo_two[0]["bar"]="value2";

NOTES:
1)  If the leading identifier on a line is a number, the output will most likely be unusable since variable names cannot begin with numbers.  You can get around this by doing something like:
$arr = array('arr' => $arr);
This will output the array as it actually is (because the key is the same name as the array) instead of just its fields.
2)  Since spaces are not allowed in variable names, they are replaced in lines' leading identifiers by the $space_replace_char parameter, '_' by default.

Hopefully someone will find this useful, if so drop me a line.  Credit and thanks go out to the people who posted their code on this manual page, especially davidpk212 at gmail dot com and phpWalter at torres dot ws.

function implode_parseable($inner_glue = "=", $outer_glue = "\n", $array = null, $prefix = "", $suffix = "", $space_replace_char = '_', $skip_empty = false, $current_loc = "", $recursion_level = 0){
  return $prefix . implode_parseable_r($inner_glue, $outer_glue, $array, $space_replace_char, $skip_empty, $current_loc, $recursion_level) . $suffix;
}

function implode_parseable_r($inner_glue = "=", $outer_glue = "\n", $array = null, $space_replace_char = '_', $skip_empty = false, $current_loc = "", $recursion_level = 0)
{
  if(is_array($array)){
    $output = array();
    foreach( $array as $key => $item ){
      if ( is_array ($item) ){
       
        //don't quote numeric indicies
        if(is_string($key)) 
          $quoted_key = "\"" . $key . "\""; 
        else 
          $quoted_key = $key;

        // This is value is an array, go and do it again!
        $level = $recursion_level + 1;
        if($recursion_level == 0){
          // can't have spaces in a variable name!
          $current_loc .= str_replace(' ', $space_replace_char, $key);
          $output[] = implode_parseable_r ($inner_glue, $outer_glue, $item,  '_', $skip_empty, $current_loc, $level);
          //start the position tracker over after every run from level 0
          $current_loc = '';
        }else{
          $current_loc .= "[" . $quoted_key . "]";
          $output[] = implode_parseable_r ($inner_glue, $outer_glue, $item,  '_', $skip_empty, $current_loc, $level);
          //remove the last index from the position tracker string after using it
          $current_loc = ereg_replace('\[[^]]*\]$', '', $current_loc);
        }

      }
      else{
        //  don't quote or []ify the base variable name,
        //  but do for all else as appropriate
        if($recursion_level != 0){
            if(is_string($key))
              $key = "\"" . $key . "\"";
            $key = "[" . $key . "]";
        }
//        echo "<br>";
//        var_dump($item);
//        echo "<br>";

        $skip_this = false;
        if($skip_empty && (!isset($item) || $item == NULL || $item == '')) $skip_this = true;

        //quote the item (which is the value of the array index) if it is a string
        if(is_string($item)) $item = "\"" . $item . "\"";

        if(!$skip_this) $output[] = $current_loc . $key . $inner_glue . $item;
      }
    }
    return implode($outer_glue, $output);
  }else{
    return $array;
  }
}
2005-05-31 23:57:54
http://php5.kiev.ua/manual/ru/function.implode.html
...and another variation of "implode_assoc" function. Just added the boolean parameter $urlencoded; if TRUE returns the array value in URL encod format. If the parameter is not given it behaves like the original function.

<?
function implode_assoc($inner_glue$outer_glue$array$skip_empty=false$urlencoded=false) {
   
$output = array();
    foreach(
$array as $key=>$item) {
        if (!
$skip_empty || isset($item)) {
            if (
$urlencoded)
               
$output[] = $key.$inner_glue.urlencode($item);
            else
               
$output[] = $key.$inner_glue.$item;
        }
    }
   
    return 
implode($outer_glue$output);
}
?>
2005-07-07 03:22:36
http://php5.kiev.ua/manual/ru/function.implode.html
I liked memandeemail's (27-Apr-2005) neat code for imploding an associative array. I have done a mod so that, by default, it returns a url query string.

<?php
function implode_with_key($assoc$inglue '='$outglue '&')
{
   
$return null;
   foreach (
$assoc as $tk => $tv$return .= $outglue.$tk.$inglue.$tv;
   return 
substr($return,1);
}
?>

Example:
<?php
$assoc_array 
= array("a" => "foo""b" => "bar""c" => "foobar");
echo (
implode_with_key($assoc_array);
?>

ouput: a=foo&b=bar&c=foobar

usage: After altering the $HTTP_GET_VARS values, I pass $HTTP_GET_VARS to the function to easily build variation urls for links and header redirects.

note: This function doesn't encode the url string or check for empty variables.
2005-08-19 21:06:40
http://php5.kiev.ua/manual/ru/function.implode.html
A little tweak on info at urbits dot com's suggestion just incase someone changes their value of $outglue:

<?php
function implode_with_key($assoc$inglue '='$outglue '&')
{
   
$return null;
   foreach (
$assoc as $tk => $tv$return .= $outglue.$tk.$inglue.$tv;
   return 
substr($return,strlen($outglue));
}
?>
2005-08-29 12:46:58
http://php5.kiev.ua/manual/ru/function.implode.html
Another variation on implode_with_key:

<?php
 
function implode_with_key($assoc$inglue '='$outglue '&')
    foreach (
$assoc as $tk => $tv) {
     
$return = (isset($return) ? $return $outglue '') . $tk $inglue $tv;
    }
    return 
$return;
  }
?>
2005-09-09 12:22:52
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
Correctly initializing all variables, this would become:

function implode_with_key($assoc, $inglue = '=', $outglue = '&'){
    $return = '';
    foreach ($assoc as $tk => $tv) {
        $return = ($return != '' ? $return . $outglue : '') .
            $tk . $inglue . $tv;
    }
    return $return;
}

Note, the return value is also well defined if $assoc is empty.

Regards
2005-09-27 10:26:14
http://php5.kiev.ua/manual/ru/function.implode.html
...and a mysql-update-statement-compatible implementation of implode_with_keys:

<?php
function implode_with_keys($glue$array$valwrap='')
    {
        foreach(
$array AS $key => $value) {
           
$ret[] = $key."=".$valwrap.$value.$valwrap;
        }
        return 
implode($glue$ret);
    }
?>

so implode_with_keys(", ", $array, "'") will output:

key1='value1', key2='value2'

and so on. Useful for UPDATE table SET key1='value1', key2='value2'
2005-10-31 06:53:54
http://php5.kiev.ua/manual/ru/function.implode.html
an implementation of adrian at foeder dot de implode_with_keys function for input and update sql statement.

function implode_param($glue, $array, $valwrap='', $mode = 0)
   {
    /*   
    if mode = 0 output is key and values
    if mode = 1 output only keys
    if mode = 2 output only values
    */
   
    switch ($mode){
        case 1:
               foreach($array AS $key => $value) {
                   $ret[] = $valwrap.$key.$valwrap;
               }
        break;
       
        case 2:
               foreach($array AS $key => $value) {
                   $ret[] = $valwrap.$value.$valwrap;
               }
        break;

        default:
        case 0:
               foreach($array AS $key => $value) {
                   $ret[] = $key."=".$valwrap.$value.$valwrap;
               }
        break;
       
    }
       
       
    return implode($glue, $ret);
}
2006-01-03 10:39:51
http://php5.kiev.ua/manual/ru/function.implode.html
An easier way of achieving the same result as implode_with_keys() - and quicker execution time:

<?
/* NOTE: $glue is not used if $is_query is true */
function implode_with_keys($array$glue$is_query false) {
    if(
$is_query == true) {
        return 
str_replace(array('['']''&'), array('%5B''%5D''&amp;'), http_build_query($array));

    } else {
        return 
urldecode(str_replace("&"$gluehttp_build_query($array)));

    }

}

echo 
implode_with_keys(array('a[1]' => 'some text''a[2]' => 'even more text'), falsetrue);
/* Will output 'a%5B1%5D=some+text&amp;a%5B2%5D=even+more+text' */
/* This won't break html validation */

echo implode_with_keys(array('a[1]' => 'foo bar''b' => 'more text'), '|');
/* Will output 'a[1]=foo bar|b=more text' */
?>
2006-05-23 12:17:16
http://php5.kiev.ua/manual/ru/function.implode.html
A Script for imploding a multideimensional Array. You give an array of separators in the first argument, and a (multidimensional) array in the second. The script will return the imploded array.

<?php
function multimplode($spacer,$array
    {
    if (!
is_array($array))
        {
        return(
$array);
        }   
    if (empty(
$spacer))
        {
        return(
multimplode(array(""),$array)); 
        }
    else
        {
       
$trenn=array_shift($spacer);
        while (list(
$key,$val) = each($array))
            {
            if (
is_array($val)) 
                {
               
$array[$key]=multimplode($spacer,$val);
                }
            }
       
$array=implode($trenn,$array);
        return(
$array);
        }
    }
?>
2006-08-12 15:15:05
http://php5.kiev.ua/manual/ru/function.implode.html
Here's my 2 matching (implode|explode)_with_key functions.
Notice, the inglue, outglue cannot appear within the keys\values.

function implode_with_key($assoc, $inglue = '>', $outglue = ',')
    {
        $return = '';
        foreach ($assoc as $tk => $tv) 
        {
            $return .= $outglue . $tk . $inglue . $tv;
        }
        return substr($return,strlen($outglue));
    }
   
   
    function explode_with_key($str, $inglue = ">", $outglue = ',')
    {
        $hash = array();
        foreach (explode($outglue, $str) as $pair)
        {           
            $k2v = explode($inglue, $pair);           
            $hash[$k2v[0]] = $k2v[1];           
        }
        return $hash;
    }

-- Tomer Levinboim
2006-09-05 17:18:55
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
Very simple function for imploding a certain column in a 2D array. Useful if you have fetched records from a database in an associative array and want to store all the values in a certain column as a string, for use with JavaScript or passing values from page to page.

$sep = the separator, such as " ", "," or "&amp;"
$array = the 2D associative array
$key = the column key, such as "id"

Feel free to add error protection

function implodeArray2D ($sep, $array, $key)
{
   
    $num = count($array);
    $str = "";
   
    for ($i = 0; $i < $num; $i++)
    {
       
        if ($i)
        {
            $str .= $sep;
        }
       
        $str .= $array[$i][$key];
       
    }
   
    return $str;
   
}
2006-10-05 05:11:33
http://php5.kiev.ua/manual/ru/function.implode.html
This is a simple function that is the same as implode except it allows you to specify two glue parameters instead of one so an imploded array would output "this, this, this and this" rather than "this, this, this, this, this".

This is useful if you want to implode arrays into a string to echo as part of a sentence.

It uses the second glue between the last two items and the first glue between all others. It will use the second glue if there are only two items to implode so it would output "this and this".

<?php

function implode2($glue1$glue2$array)
{
    return ((
sizeof($array) > 2)? implode($glue1array_slice($array0, -2)).$glue1 "").implode($glue2array_slice($array, -2));
}

//example below

$array = array("Monday""Tuesday");
echo 
"1: ".implode2(', '' and '$array)."<br />";

$array = array("Mon""Tue""Wed""Thu""Fri");
echo 
"2: ".implode2(', '' &amp; '$array)."<br />";

$array = array( 123410);
echo 
"3: ".implode2(' + '' = '$array)."<br />";

?>

This outputs

1: Monday and Tuesday
2: Mon, Tue, Wed, Thu & Fri
3: 1 + 2 + 3 + 4 = 10
2006-11-23 06:43:35
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
The english_list() implementation of davidpk212 at gmail dot com, Andy Morris, and tshort at cisco dot com does not handle the case of a two-element array with Oxford comma.  Example:

<?php
english_list
(array ('a''b'), true// == 'a, and b'
// should be 'a and b'
?>

Here's another implementation that addresses this issue, uses pass-by-reference without modifying the array, and illustrates yet another approach to solving the problem:

<?php
function english_list(&$array$useOxfordComma false) {
   
$count = (is_array($array) ? count($array) : 0);
    if (
<= $count) {
       
$last end($array);
       
$list prev($array) . ($useOxfordComma ', and ' ' and ') . $last;
        while (
$v prev($array)) {
           
$list $v ', ' $list;
        }   
    } else if (
== $count) {
       
$last end($array);
       
$list prev($array) . ' and ' $last;
    } else if (
== $count) {
       
$list end($array);
    } else { 
        return 
'';
    }       
             
   
reset($array);
    return 
$list;
}           
?>

Run times for this version are comparable to the run times for heir earlier posted versions.
2006-11-23 08:33:04
http://php5.kiev.ua/manual/ru/function.implode.html
Note that PHP uses copy-on-write so passing parameters (even array parameters) by reference gains you no performance benefit, and in fact in some cases can HURT performance.

For example:

php > $array = array('a','s','d','f');
php > $start = microtime(true); for($i=0; $i<1000000; $i++) byref($array); echo microtime(true)-$start;
2.40807890892
php > $start = microtime(true); for($i=0; $i<1000000; $i++) byval($array); echo microtime(true)-$start;
1.40822386742
2007-01-04 08:43:33
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
And adding one more case to drewish at katherinehouse dot com's code to deal with the two-element case "a and b":

<?php
case 2:
    return 
reset($array).' and '.end($array);
?>

Of course, then one can start considering Oxford rules again, and maybe testing that the argument really is an array....

<?php
function english_list($array$useOxfordComma=false)
{
    if(!
is_array($array))
        return 
'';
    switch(
count($array))
    {
    case 
0:
        return 
'';
    case 
1:
       
// This may not be a normal numerically-indexed array.
       
return reset($array);
    case 
2:
        return 
reset($array).' and '.end($array);
    default:
       
$last array_pop($array);
        return 
implode(', '$array).($useOxfordComma?',':'').' and '.$last;
    }
}
?>
2007-03-19 16:52:30
http://php5.kiev.ua/manual/ru/function.implode.html
this is a little function i made to implode an array based on key. its main purpose is to implode elements within
a multi-dimensional array. its slightly different than some of the other examples because it makes use of some
PHP SPL features. if your not using PHP5, this definitely won't work for you.

let me know what you think!

<?php
function implode_by_key($glue$keyname$pieces)
{

   
// create a new recursive iterator to get array items
   
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($pieces));

   
$arr = array();

    foreach(
$it AS $element) {

        if (
$it->key() == $keyname) {

           
$arr[] = $it->current();

        }

    }

    return 
implode($glue$arr);

}

// here is an example

$array = array(
            array(
'somekey' => 'somevalue'),
            array(
                array(
'key2' => 'anoter value'),
                array(
'key2' => 'another sub value'),
                array(
                    array(
'key3' => 'asdlkfs jdafajdshf aoufiahsdlkfjsadf'),
                    array(
                        array(
'key4' => 'this is key 4 - 1'),
                        array(
'key4' => 'this is key 4 - 2'),
                        array(
'key4' => 'this is key 4 - 3'),
                        array(
                            array(
'key5' => 'asdfkajsdflkasjdfklajshfkljasfhasdfasdf'),
                            array(
'key5' => 'asdfkajsdflkasjdfklajshfkljasfhasdfasdf'),
                        )                                   
                    )
                )

            )
        );

echo 
implode_by_key('<br/>''key4'$array);
?>

This outputs:

this is key 4 - 1
this is key 4 - 2
this is key 4 - 3
2007-03-20 14:09:59
http://php5.kiev.ua/manual/ru/function.implode.html
in response to Brian, building a POST/GET string from an assoc array is easily done with the builtin http_build_query...as the example from its doc page shows:

<?php
$data 
= array('foo'=>'bar',
             
'baz'=>'boom',
             
'cow'=>'milk',
             
'php'=>'hypertext processor');

echo 
http_build_query($data); // foo=bar&baz=boom&cow=milk&php=hypertext+processor
?>

of course, the builtin function also urlencodes the string it returns, which Brian's function did not.
2007-06-14 11:46:37
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
I have resolved an issue in SquirrelMail.  The problem seemed to be with the implode command.  Apparently you do not want to use this function with a large array as SquirellMail attempted to do.  This only was an issue with some of the email attachments larger that 2MB.

In /src/move_messages.php, replace the line line that says 

$body = implode('', $body_a); 

With :

// Dennis Day's custom code
                $body = "";
                foreach($body_a as $body_a_key=>$body_a_value){
                                $body .= $body_a_value;
                }
// End Dennis Day's custom code

// Original Bad Code
//              $body = implode('', $body_a);
2007-07-02 17:39:10
http://php5.kiev.ua/manual/ru/function.implode.html
I came up with this nifty function to implode an Iterator or class that implements IteratorAggregate:

function implode_iterator($sep = '', $it) {
    $a = array();
   
    if(!$it instanceof Traversable) {
        throw new UnexpectedValueException('$it must implement Traversable.');
    }
   
    if($it instanceof IteratorAggregate) {
        $a = iterator_to_array($it, FALSE);
    } else if($it instanceof Iterator) {
        foreach($it as $val) {
            $a[] = $val;
        }
    }
   
    return implode($sep, $a);
}
2007-07-04 13:36:46
http://php5.kiev.ua/manual/ru/function.implode.html
This is my quick function to create a list, English style, but will accept any glue, so you could use 'or', or even 'or though, it could be', etcetera. It should also support PHP 4, although I haven't tested it; it doesn't use the PHP 5 negative substr() trick. 

<?php

/**
 * Quick script to join items in an array, English
 * style; using the "one, two and three" style.
 *
 * Copyright 2007 Thomas O. Feel free to redistribute
 * so long as this copyright remains. 
 */

function implode_ea($glue_punct$glue_word$array) {
   
// Implode the entire array
   
$result implode($glue_punct$array);

   
// Check the length of the array
   
if(count($array) > 1) {
       
// Calculate the amount needed to trim
       
$trimamount strlen($array[count($array) - 1]) + strlen($glue_punct);

       
// Trim the imploded string
       
$result substr($result0strlen($result) - $trimamount); // PHP 4 compatible
       
$result "$result $glue_word " $array[count($array) - 1];

       
// Return the result
       
return $result;
    } else {
       
// In this case, the array cannot be splitted by a
        // word or punctuation, because it is too small.
       
return $result;
    }
}

echo 
implode_ea(", ""and", array("one""two""three"));
?>

(implode_ea stands for 'Implode, English And style')

Hope this helps,
Tom
2007-07-09 16:05:17
http://php5.kiev.ua/manual/ru/function.implode.html
This code implodes same as the PHP built in except it allows you to do multi dimension arrays ( similar to a function below but works dynamic :p.

<?php

function implode_md($glue$array$array_path='')
{
    if ( !empty(
$array_path) )
    {
       
$array_path explode('.'$array_path);
       
        if ( ( 
$array_path_sizeof sizeof($array_path) ) < )
        {
            return 
implode($glue$array);
        }
    }
    else
    {
        return 
implode($glue$array);
    }
   
   
$str '';
   
   
$array_sizeof sizeof($array) - 1;
   
    for ( 
$i 0$i $array_sizeof$i++ )
    {
       
$value $array$i ];
       
        for ( 
$j 0$j $array_path_sizeof$j++ )
        {
           
$value =& $value$array_path$j ] ];
        }
       
       
$str .= $value $glue;
    }
   
   
$value $array$array_sizeof ];
   
    for ( 
$j 0$j $array_path_sizeof$j++ )
    {
       
$value =& $value$array_path$j ] ];
    }
   
   
$str .= $value;
   
    return 
$str;
}

?>

And heres an example on how to use this

<?php

$arr 
= array();
$arr[]['data']['id'] = 'a';
$arr[]['data']['id'] = 'b';
$arr[]['data']['id'] = 'c';
$arr[]['data']['id'] = 'd';
$arr[]['data']['id'] = 'e';
$arr[]['data']['id'] = 'f';
$arr[]['data']['id'] = 'g';

echo 
implode_md(','$arr'data.id');

?>

The output of this code should be

'a,b,c,d,e,f,g'

When you want to work with more dimensions... say for example you have an array that is like this

<?php

$arr
=array();
$arr[0]['game']['pc']['fps']['idsoftware'] = 'Quake';
$arr[1]['game']['pc']['fps']['idsoftware'] = 'Quake II';
$arr[2]['game']['pc']['fps']['idsoftware'] = 'Quake III Arena';

?>

on the third parameter... as a string you simply type in

<?php

echo implode_md(', '$arr'game.pc.fps.idsoftware');

?>

and the output should be

'Quake, Quake II, Quake III Arena'

Enjoy ;)
2007-10-07 08:42:37
http://php5.kiev.ua/manual/ru/function.implode.html
Below is the function for making an English-style list from an array, seems to be simpler than some of the other examples I've seen.

<?php
function ImplodeProper($arr$lastConnector 'and')
{
  if( !
is_array($arr) or count($arr) == 0) return '';
 
$last array_pop($arr);
  if(
count($arr))
    return 
implode(', ',$arr).", $lastConnector $last";
  else
    return 
$last
}
?>

Examples:
<?
   
print ImplodeProper(array()).'<br>';
   print 
ImplodeProper(array('foo')).'<br>';
   print 
ImplodeProper(array('foo','bar')).'<br>';
   print 
ImplodeProper(array('for','bar','bleh')).'<br>';
?>

Yields:

foo
foo, and bar
for, bar, and bleh
2007-10-10 18:42:22
http://php5.kiev.ua/manual/ru/function.implode.html
suppose we have array $content with total size of 10Mb of text.

then,
  $content = join($content);
will run about 23 sec (on my machine -- athlon xp 2600+, 1.5 Gb ram)

and
  file_put_contents("tempfile", $content);
  $content = file_get_contents("tempfile");
will run for 0.12 sec (same machine).

so, think carefully about speed.
2007-11-09 13:50:32
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
My take on a simple english list function - it's similar to what's already here, but calls count less

function x_implode_eng_list($array, $glue=', ', $final=' and '){
    //takes an array and outputs an English style list
    //perform the count once
    $count = count($array);
    //make sure it's an array and has content
    if((!is_array($array)) || ($count == 0)) {
        return '';
    } else {
        //pop off the end regardless of length
        $end = array_pop($array);
        //if there's more than one, implode the remainder using glue and append $end
        if($count>1){
            return implode($glue, $array) . $final . $end;
        } else {
            //only one value, return the popped end element
            return $end;
        }
    }
}
$names[] = 'bob';
$names[] = 'john';
$names[] = 'lucy';
echo x_implode_eng_list($names); //will output bob, john and lucy

echo x_implode_eng_list($names, ', ', ' or '); //will output bob, john or lucy
2008-01-12 22:00:09
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
So I looked through all the problem solutions  posted here, and combined them into one nice recursive function.

<?php

function implode_md$glue$array$key NULL$list NULL )
{
    if( !
is_array$array ) ) 
        return 
$array;
    if( !
sizeof$array ) ) 
        return 
"";
    if( !
is_null$key ) )
    {
        if( 
strpos$key"." ) )
        {
           
$keys array_reverseexplode"."$key ) );
           
$currentKey array_pop$keys );
            if( 
sizeof$keys ) ) $keys implode"."$keys );
            else 
$keys implode""$keys );
        }
        else
        {
           
$currentKey $key;
           
$keys NULL;
        }
        if( 
array_key_exists$currentKey$array ) ) 
            return 
implode_md$glue$array[$currentKey], $keys$list );
        else 
            return 
"";
    }
    if( !empty( 
$list ) )
    {
       
$last array_pop$array );
        if( 
count$array ) ) 
            return 
implode_md$glue$array$key ) . " $list $last";
        else 
            return 
$last;
    }
   
$ret = array();
    for( 
$i 0$i sizeof$array ); $i++ )
        if( 
is_array$array[$i] ) ) $ret[] = implode_md$glue$array[$i], $key$list );
        else 
$ret[] = $array[$i];
    return 
implode$glue$ret );
}

?>
2008-02-18 17:41:30
http://php5.kiev.ua/manual/ru/function.implode.html
implode() can't be used for simplexml's array but foreach() does the thing, make new implode function with foreach() will resolve this problem. use strval() to reset SimpleXMLElement object to a simple string variable.

<?php
function implode2($glue=""$var){
    if (
$var){
        foreach (
$var as $value){
           
$array[]=strval($value);
        }
        return 
implode($glue$array);
    } 
    else return 
false;
}
?>
2008-03-19 12:39:41
http://php5.kiev.ua/manual/ru/function.implode.html
I'm new to PHP, coming from Perl and I already had a problem once when I wanted to join some strings. In perl you can use join to join a list (which can be an array and/or a list of strings and/or hashes), where PHP does this only with arrays. That annoyed me. 
I could not find any code which did this, so I created my own join, based on Perl's join function. It is called p_join().

<?php

/* is_assoc_array and is_sequential_array are STOLEN from:
 * http://nl3.php.net/manual/en/function.is-array.php#73505 */
function is_assoc_array($var) {
        return (
array_merge($var) !== $var || !is_numeric(implode(array_keys($var))));
}

function 
is_sequential_array($var) {
        return (
array_merge($var) === $var && is_numeric(implode(array_keys($var))));
}

function 
_p_join_assoc($sep$hash) {
       
$result "";
        foreach (
$hash as $k => $v) {
               
$result .= $sep $k $sep $v ;
        }
        return 
$result;
}

function 
_p_join_array($sep$array) {
       
# Turn off notices and return to the old loglevel once we're done.
        # This is because we stringify an array in some cases..
       
$old_error_reporting error_reporting(E_ALL E_NOTICE);
       
$result join($sep$array);
       
error_reporting($old_error_reporting);
        return 
$result;
}

function 
p_join() {

       
$args func_get_args();

        if (
count($args) > 1) {
               
$result     "";
               
$sep array_shift($args);

                foreach (
$args as $val) {
                        if (
is_array($val)) {
                                if (
is_assoc_array($val)) {
                                       
$result .= _p_join_assoc($sep$val);
                                } else {
                                       
$result .= $sep  _p_join_array($sep$val);
                                }
                                continue;
                        }
                       
$result .= $sep $val;
                }
               
# $result will always start with a $sep, so remove it..
               
return substr_replace($result"" ,0strlen($sep));
        }

       
trigger_error(sprintf("%s requires at least 2 parameters",
         
__FUNCTION__), E_USER_WARNING);
        return 
null;
}

/* And some example code */

print p_join(",""string", array("Key" => "Value""Key 2" => "Value 2"),
  array(
"Hello", array("in""hello""world"), "array"), "string 2") . "\n";

/* Watch out, prints de indices when it you supply a mixed array */
print p_join(",", array(1,2,"Green" => "Apple" , array(1,2))) . "\n";

print 
"Warning.. ";
print 
p_join(",");
?>
2008-04-01 19:36:03
http://php5.kiev.ua/manual/ru/function.implode.html
A usefull version of implode() when you need to surround values, for example when you are working with nodes (HTML, XML)

<?php
function myImplode($before$after$glue$array){
   
$nbItem count($array);
   
$i 1;
    foreach(
$array as $item){
        if(
$i $nbItem){
           
$output .= "$before$item$after$glue";
        }else 
$output .= "$before$item$after";
       
$i++;
    }
    return 
$output;
}

$an_array = array('value1','value2');
print 
myImplode("<a href=\"#\">","</a>"," > "$an_array);
?>

output : <a href="#">value1</a> > <a href="#">value2</a>
2008-05-27 10:12:22
http://php5.kiev.ua/manual/ru/function.implode.html
Refering to the previous post, here an optimized version:

<?php

function implode_wrapped($before$after$glue$array){
   
$output '';
    foreach(
$array as $item){
       
$output .= $before $item $after $glue;
    }
    return 
substr($output0, -strlen($glue));
}

?>
2008-07-15 22:47:40
http://php5.kiev.ua/manual/ru/function.implode.html
This is a recursive implode function that can be used on multi-dimensional arrays. The explode function has also obeen included.

<?php
               
//  Can implode an array of any dimension
        //  Uses a few basic rules for implosion:
        //        1. Replace all instances of delimeters in strings by '/' followed by delimeter 
        //        2. 2 Delimeters in between keys
        //        3. 3 Delimeters in between key and value
        //        4. 4 Delimeters in between key-value pairs
       
function implodeMDA($array$delimeter$keyssofar '') {
           
$output '';
            foreach(
$array as $key => $value) {
                if (!
is_array($value)) {
                   
$value str_replace($delimeter'/'.$delimeter$value);
                   
$key str_replace($delimeter'/'.$delimeter$key);
                    if (
$keyssofar != ''$key $key.$delimeter.$delimeter;
                   
$pair $key.$keyssofar.$delimeter.$delimeter.$delimeter.$value;
                    if (
$output != ''$output .= $delimeter.$delimeter.$delimeter.$delimeter;
                   
$output .= $pair;
                }
                else {
                    if (
$output != ''$output .= $delimeter.$delimeter.$delimeter.$delimeter;
                    if (
$keyssofar != ''$key $key.$delimeter.$delimeter;
                   
$output .= $this->implodeMDA($value$delimeter$key.$keyssofar);
                }
            }
            return 
$output;
        }
       
       
       
//  Can explode a string created by corresponding implodeMDA function
        //  Uses a few basic rules for explosion:
        //        1. Instances of delimeters in strings have been replaced by '/' followed by delimeter 
        //        2. 2 Delimeters in between keys
        //        3. 3 Delimeters in between key and value
        //        4. 4 Delimeters in between key-value pairs
       
function explodeMDA($string$delimeter) {
           
$output = array();
           
$pair_delimeter $delimeter.$delimeter.$delimeter.$delimeter;
           
$pairs explode($pair_delimeter$string);
            foreach (
$pairs as $pair) {
               
$keyvalue_delimeter $delimeter.$delimeter.$delimeter;
               
$keyvalue explode($keyvalue_delimeter$pair);
               
$key_delimeter $delimeter.$delimeter;
               
$keys explode($key_delimeter$keyvalue[0]);
               
$value str_replace('/'.$delimeter$delimeter$keyvalue[1]);
               
$keys[0] = str_replace('/'.$delimeter$delimeter$keys[0]);
               
$pairarray = array($keys[0] => $value);
                for (
$counter 1$counter count($keys); $counter++) {
                   
$pairarray = array($keys[$counter] => $pairarray);
                }
               
$output array_merge_recursive($output$pairarray);
            }
            return 
$output;
        }
?>
2008-07-23 09:36:13
http://php5.kiev.ua/manual/ru/function.implode.html
I found this pretty useful so I wouldn't have to hardcode things:
<?php
function implode_get() {
   
$first true;
   
$output '';
    foreach(
$_GET as $key => $value) {
        if (
$first) {
           
$output '?'.$key.'='.$value;
           
$first false;
        } else {
           
$output .= '&'.$key.'='.$value;   
        }
    }
    return 
$output;
}

echo 
'<form action='.$_SERVER['PHP_SELF'].implode_get()' method=post>';
?>
2008-07-25 08:38:55
http://php5.kiev.ua/manual/ru/function.implode.html
Many of the functions below can be simplified using this short function:

<?php
function array_implode($arrays, &$target = array()) {
    foreach (
$arrays as $item) {
        if (
is_array($item)) {
           
array_implode($item$target);
        } else {
           
$target[] = $item;
        }
    }
    return 
$target;
}

$a = array('a''b', array('c''d', array('e'), 'f'), 'g', array('h'));

echo 
join(' - 'array_implode($a));
?>

The outputs:

<?php

h

?>
2008-07-30 07:30:00
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
superstuntguy below would save himself and his server a lot of time just by using $_SERVER['QUERY_STRING'] (see http://uk.php.net/manual/en/reserved.variables.server.php), as in:

<?php
echo '<form action='$_SERVER['PHP_SELF'], '?'$_SERVER['QUERY_STRING'], ' method=post>';
?>

Note: using commas instead of full-stops (periods) between strings for echo is marginally more efficient as echo can then simply pop the substrings off the stack avoiding the tincy-wincy extra overhead of string concatenation.
2008-08-16 11:51:58
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
Here's my version of the english implode function, it's quite crafty so I thought I'd share it...

<?php
   
#
    # Transforms an array to an english list:
    # This, This and This
    #
   
function array_to_english $list$glueword='and' ) {
       
       
$string false;
       
        foreach ( 
array_reverse $list ) as $index=>$value ) {
           
$string "$value$glue$string";
            if ( 
$index == $glue " $glueword ";
            if ( 
$index == $glue ', ';
        }
       
        return 
$string;
    }
?>
2008-09-12 08:09:56
http://php5.kiev.ua/manual/ru/function.implode.html
I was fiddling around on a project and created an associative array implosion function that incorporates several of the ideas from this page, but which also adds a whack of nifty options. Unfortunately, the documentation for it made the post to long to display on this page, so I've provided the example on my site. Enjoy!

http://emanaton.com/code/php/implode_assoc
2008-10-09 23:27:52
http://php5.kiev.ua/manual/ru/function.implode.html
This function is much more elegant and fast. It converts array to the list with 'and' at the end:

<?php
function ImplodeToEnglish ($array) {
   
// sanity check
   
if (!$array || !count ($array))
        return 
'';

   
// get last element   
   
$last array_pop ($array);

   
// if it was the only element - return it
   
if (!count ($array))
        return 
$last;   

    return 
implode (', '$array).' and '.$last;
}
?>
2008-11-06 02:48:22
http://php5.kiev.ua/manual/ru/function.implode.html
For anyone looking for a good method to wrap each element before imploding it, I use this method:

<?php
function wrap_each(&$item)
{
   
$item "'$item'";
}

array_walk($array'wrap_each');
$array_csv implode(","$array);
?>
2008-12-29 01:04:53
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
I've implemented the function implode (it's easy):
<?php
function mt_implode($char,$array)
{
   
$lem array_keys($array);
   
$char htmlentities($char);
    for(
$i=0;$i<sizeof($lem);$i++) {
       
$str .= ($i == sizeof($lem)-1) ? $array[$lem[$i]] : $array[$lem[$i]].$char;
    }
    return 
$str;
}
?>

Have fun
2009-01-06 04:57:50
http://php5.kiev.ua/manual/ru/function.implode.html
I have improved crashinside's function for db use

function mt_implode($char,$array,$fix='',$addslashes=false)
{
    $lem = array_keys($array);
    $char = htmlentities($char);
    for($i=0;$i<sizeof($lem);$i++) {
      if($addslashes){
        $str .= $fix.(($i == sizeof($lem)-1) ? addslashes($array[$lem[$i]]).$fix : addslashes($array[$lem[$i]]).$fix.$char);
      }else{
        $str .= $fix.(($i == sizeof($lem)-1) ? $array[$lem[$i]].$fix : $array[$lem[$i]].$fix.$char);
      }
    }
    return $str;
}

$array = array("apple", "orange", "tree", "Sant' Anna");
echo mt_implode(', ', $array,'"',true); 

// "apple", "orange", "tree", "Sant\' Anna"
2009-03-13 03:26:20
http://php5.kiev.ua/manual/ru/function.implode.html
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
Found it very useful when inserting sql/mysql rows,

<?php
$values 
= array('firstname'=>'firstname_value','lastname'=>'lastname_value');

sprintf('INSERT INTO %s (%s) VALUES ("%s")''table_name'implode(', 'array_map('mysql_escape_string'array_keys($values))), implode('", "',array_map('mysql_escape_string'$values)));

//that gives you: INSERT INTO table_name (firstname, lastname) VALUES ("firstname_value", "lastname_value")

?>
Very useful when dealing with tables with many columns.
2009-08-04 08:39:21
http://php5.kiev.ua/manual/ru/function.implode.html
As "john" pointed out on 2004 Apr 26, implode does not always work in a way that could be considered intuitive.

You may need to sort your elements with ksort, or write a longer routine to fill in any "gaps". See this example:

<?php
$a 
= array(1=>'one'7=>'seven'5=>'five');

$b implode (','$a);

ksort ($a);

$c implode (','$a);

$highest max(array_keys($a));
for (
$i 0$i <= $highest; ++$i):
  if (! isset(
$a[$i])):
   
$a[$i] = '';
  endif;
endfor;
ksort ($a);

$d implode (','$a);

print 
"\$b = '$b'<br>\n";
print 
"\$c = '$c'<br>\n";
print 
"\$d = '$d'<br>\n";

/*
output:
$b = 'one,seven,five'
$c = 'one,five,seven'
$d = ',one,,,,five,,seven'
*/
?>

Or, as a function:

<?php
function ensure (&$a$filler '') {

 
// given: array $a with numerical keys
  // return: $a with keys sorted numerically and any gaps filled-in

   
$highest max(array_keys($a));
   for (
$i 0$i <= $highest; ++$i):
     if (! isset(
$a[$i])):
       
$a[$i] = $filler;
     endif;
   endfor;
   
ksort ($a);

// end function ensure

// usage:
// ensure($foo);
// ensure($bar, 0);
?>
2009-08-07 07:21:16
http://php5.kiev.ua/manual/ru/function.implode.html
I was a little worried about the multi-dimensional array implodes listed here, as they are using 'for' loops, which is bad programming practice as arrays are not always nice and neat.

I hope this helps

<?php
function multi_implode($glue$pieces)
{
   
$string='';
   
    if(
is_array($pieces))
    {
       
reset($pieces);
        while(list(
$key,$value)=each($pieces))
        {
           
$string.=$glue.multi_implode($glue$value);
        }
    }
    else
    {
        return 
$pieces;
    }
   
    return 
trim($string$glue);
}

?>
2009-11-18 09:54:27
http://php5.kiev.ua/manual/ru/function.implode.html
Recursive Implode

<?php

function r_implode$glue$pieces )
{
  foreach( 
$pieces as $r_pieces )
  {
    if( 
is_array$r_pieces ) )
    {
     
$retVal[] = r_implode$glue$r_pieces );
    }
    else
    {
     
$retVal[] = $r_pieces;
    }
  }
  return 
implode$glue$retVal );
}

$test_arr = array( 01, array( 'a''b' ), array( array( 'x''y'), 'z' ) );
echo 
r_implode','$test_arr ) . "\n";
$test_arr = array( );
echo 
r_implode','$test_arr ) . "\n";
?>
2010-02-08 18:29:13
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
If you need to output an array of strings inclosed in quotes (to convert it from php to JavaScript for instance), you can use this simple method:

var js_array = new Array("<?php echo implode('","',$php_array)?>");
2010-04-26 10:17:58
http://php5.kiev.ua/manual/ru/function.implode.html
You don't need to do anything funny with implode() to get a php array into javascript - just use json_encode().
2010-09-03 00:09:18
http://php5.kiev.ua/manual/ru/function.implode.html
Small function when you just want to implode on the keys of an array. Especially helpful when you for instance create an array for database inserting in which the keys point to table row names.

Uses same function argument names as this documentation states for implode. 

<?php
function implode_key($glue ""$pieces = array()) {
   
$arrK array_keys($pieces);
    return 
implode($glue$arrK);
}
?>
2010-11-09 03:38:22
http://php5.kiev.ua/manual/ru/function.implode.html
I've seen some code below for imploding an associative array.

Please note that http_build_query() will take care of that for you:
http://php.net/http_build_query

Happy coding!
2011-02-11 17:19:45
http://php5.kiev.ua/manual/ru/function.implode.html
Автор:
It is also possible to implode an associative array using the following code (if you do not like (mis-)using http functions):

<?php

$assoc_array 
= array("Key1" => "Value1""Key2" => "Value2");

$new_array array_map(create_function('$key, $value''return $key.":".$value." # ";'), array_keys($assoc_array), array_values($assoc_array));

print 
implode($new_array);

?>

Which will output:

Key1:Value1 # Key2:Value2 #
2011-05-07 01:42:06
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
Hello there.
First, forgive me for my English if I write anything wrong. I'm brazilian.

I've made a recursive implode for multidimensional arrays. The $glue may be either an array or a string. If array, each element will be used as glue for each level of $pieces. If count($glue) is less than number of levels of $pieces, the last glue will be used for the remainder levels.

<?php

function implode_r($glue$pieces){
       
$return "";

        if(!
is_array($glue)){
           
$glue = array($glue);
        }
       
       
$thisLevelGlue array_shift($glue);

        if(!
count($glue)) $glue = array($thisLevelGlue);
       
        if(!
is_array($pieces)){
            return (string) 
$pieces;
        }
       
        foreach(
$pieces as $sub){
           
$return .= implode_r($glue$sub) . $thisLevelGlue;
        }

        if(
count($pieces)) $return substr($return0strlen($return) -strlen($thisLevelGlue));

        return 
$return;
    }

//Example
$arr = array(
    array(
       
'SecondLevelFirstElement',
       
'SecondLevelSecondElement'
   
),
   
'FirstLevelFirstElement',
   
'FirstLevelSecondElement'
);

echo 
implode_r(array("-|-""_"));

?>

The output string will be:
"SecondLevelFirstElement_SecondLevelSecondElement-|-FirstLevelFirstElement-|-FirstLevelSecondElement"
2011-08-19 07:32:05
http://php5.kiev.ua/manual/ru/function.implode.html
for dealing with tables:

<?php
$values 
= array('firstname'=>'firstname_value','lastname'=>'lastname_value');

sprintf('INSERT INTO %s (%s) VALUES ("%s")''table_name'implode(', 'array_map('mysql_escape_string'array_keys($values))), implode('", "',array_map('mysql_escape_string'$values)));

//that gives you: INSERT INTO table_name (firstname, lastname) VALUES ("firstname_value", "lastname_value")

?>
2011-10-07 08:38:36
http://php5.kiev.ua/manual/ru/function.implode.html
Here is a function to implode and array including the key and value pair.

<?php
/**
 * Implode an array with the key and value pair giving
 * a glue, a separator between pairs and the array
 * to implode.
 * @param string $glue The glue between key and value
 * @param string $separator Separator between pairs
 * @param array $array The array to implode
 * @return string The imploded array
 */
function array_implode$glue$separator$array ) {
    if ( ! 
is_array$array ) ) return $array;
   
$string = array();
    foreach ( 
$array as $key => $val ) {
        if ( 
is_array$val ) )
           
$val implode','$val );
       
$string[] = "{$key}{$glue}{$val}";
       
    }
    return 
implode$separator$string );
   
}
?>

You can, for example, encode an array to be sent as an URL query using this:
<?php
$query 
url_encodearray_implode'=''&'$array ) );
?>

Or if you want to output an HTML element attributes:
<?php
echo '<input '.array_implode'="''" '$array ).' />';
?>

Hope it can help someone!
2011-10-08 13:02:37
http://php5.kiev.ua/manual/ru/function.implode.html

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