MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

implode

(PHP 3, PHP 4, PHP 5)

implode -- Une elementos de una matriz mediante una cadena

Descripción

string implode ( string elemento_union, array trozos )

Devuelve una cadena que contiene una representación de todos los elementos de la matriz en el mismo orden, pero con la cadena elemento_union en medio de los mismos.

Ejemplo 1. Ejemplo de implode()

<?php

$array
= array('apellido', 'email', 'telefono');
$separado_por_comas = implode(",", $array);

echo
$separado_por_comas; // apellido,email,telefono

?>

Nota: La función implode() puede, por razones históricas, acceptar sus parámetros en cualquier orden. Sin embargo, para mantener la consistencia con la función explode(), se recomienda emplear los parámetros en el orden indicado.

Nota: Desde la versión de PHP 4.3.0, el parámetro elemento_union es opcional y su valor por defecto es una cadena vacía (''). De todas formas, para mantener la compatibilidad con versiones anteriores, se recomienda indicar siempre los 2 parámetros definidos.

Nota: Esta función es segura binariamente.

Vea también explode() y split().



add a note add a note User Contributed Notes
implode
ale5000 at tiscali dot it
21-Aug-2006 05:43
There is a simpler way without implode:

function arrayToString($array)
{
   return var_export($array, true);
}

function stringToArray($string)
{
   return eval("return ".$string.";");
}

$string = arrayToString($array);
$array = stringToArray($string);
ale5000 at tiscali dot it
21-Aug-2006 05:21
There is a simpler way without implode:

function arrayToString($array)
{
   return var_export($array, true);
}

function stringToArray($string)
{
   return eval("return ".$string.";");
}

$string = arrayToString($array);
$array = stringToArray($string);
worldwideweb dot C-Kling dot de
12-Aug-2006 12:15
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);
       }
   }
?>
adnan at barakatdesigns dot net
23-May-2006 09:17
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("&", $glue, http_build_query($array)));

   }

}

echo
implode_with_keys(array('a[1]' => 'some text', 'a[2]' => 'even more text'), false, true);
/* 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' */
?>
dabduster at gmail dot com
03-Jan-2006 08:39
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);
}
Hotmail resident Tree2054
08-Dec-2005 11:57
Combining into one function:

function implode_with_options($assoc_array, $prefix = '', $k_v_glue = '', $vwrap = '', $seperator = '')
{
   foreach ($assoc_array as $k => $v)
   {
       $tmp[] = $k . $k_v_glue . $vwrap . $v . $vwrap;
   }
   return $prefix . implode($seperator, $tmp);
}

$items = array('Apples', 'number' => 3, 'Vehicle' => '');

// For a query string:
echo implode_with_options($items, '?', '=', '', '&');

/**
 * Produces
 * ?0=Apples&number=3&Vehicle=
 */

// For a SQL query
echo implode_with_options($items, '', '=', '"', ', ');

/**
 * Produces
 * 0="Apples", number="3", Vehicle=""
 */
adrian at foeder dot de
31-Oct-2005 04:53
...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'
Peter Hopfgartner
27-Sep-2005 07:26
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
php at josh dot jeppsons dot org
09-Sep-2005 09:22
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;
  }
?>
pr10n at spymac dot com
29-Aug-2005 09:46
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));
}
?>
info at urbits dot com
19-Aug-2005 06:06
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.
cristianDOTzuddas [AT] gmailDOTcom
07-Jul-2005 12:22
...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);
}
?>
sam dot bledsoe at nosp at nn dot gmail dot com
31-May-2005 08:57
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;
  }
}
Klába
31-May-2005 05:42
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);
}
killroy at g m a i l dot c o m
16-May-2005 01:29
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);
}
tshort at cisco dot com
29-Apr-2005 07:20
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;
}
Andy Morris
28-Apr-2005 05:27
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.
tshort at cisco dot com
28-Apr-2005 01:54
/*
  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;
}
Andy Morris
28-Apr-2005 10:19
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(), 1 )."<br>";
echo
english_list( array("foo"), 1 )."<br>";
echo
english_list( array("foo", "bar"), 0 )."<br>";
echo
english_list( array("a" => "foo", "b" => "bar", "c" => "foobar"), 1 )."<br>";
echo
english_list( array("foo", "bar", "foobar", "barfoo"), 0 )."<br>";
?>
memandeemail at gmail dot com
27-Apr-2005 06:06
/**
     * 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);
   }
davidpk212 at gmail dot com
14-Apr-2005 08:36
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
01-Apr-2005 06:07
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;
}
php.net {at} nr78 {dot} net
30-Mar-2005 06:50
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());

?>
stefan
03-Mar-2005 09:47
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)"
?>
Geoff Eby
03-Mar-2005 08:29
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"
?>
phpWalter at torres dot ws
14-Sep-2004 11: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 11: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 02: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 01: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 11: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 10: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
30-May-2003 07: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 10: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 10: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 12: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
14-Mar-2002 10: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

Citas célebres

Los fenómenos del mundo exterior objetivo se reflejan en el cerebro del hombre por medio de los órganos de sus cinco sentidos.

Mao Zedong
Dictador chino
(1893-1976)
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_070.jpg
Contenidos Web

Chiste de... Camareros
Cena ovípara

Ayer tome una cena ovípara.

- ¿Será opípara?

- No, es que me costó un huevo.
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_018.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake Mania
Jugadores: 6835
Categoría del juego: Acción
Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero.
Rainbow WebRainbow Web
Jugadores: 2199
Categoría del juego: Puzzles
Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente.
Mahjongg FortunaMahjongg Fortuna
Jugadores: 12462
Categoría del juego: Solitarios
Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta.
Chainz 2Chainz 2
Jugadores: 6955
Categoría del juego: Puzzles
Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más.
DeliciousDelicious
Jugadores: 4405
Categoría del juego: Acción
Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues!
BookwormBookworm
Jugadores: 4568
Categoría del juego: Palabras
Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos!
ZumaZuma
Jugadores: 4976
Categoría del juego: Acción
Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás!
Jewel of AtlantisJewel of Atlantis
Jugadores: 3798
Categoría del juego: Puzzles
Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis.
Jewel QuestJewel Quest
Jugadores: 3727
Categoría del juego: Puzzles
Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos!
Bejeweled 2Bejeweled 2
Jugadores: 3659
Categoría del juego: Puzzles
Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0429.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail
Sucedió el...

30 de agosto de 1617

Fallece Santa Rosa de Lima, por la que se celebra el "Día de la Patrona de América".
Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid fallera mayor campus party alcacer feria valencia fernando alonso loterias dinero inversiones violencia de genero makro empresas cartera soledad tolerancia metro valencia gobierno de españa violencia de genero UIMP navidad