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.
implode
(PHP 4, PHP 5)
implode — Join array elements with a string
Description
Join array elements with a glue string.
Note: implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.
Parameters
- glue
-
Defaults to an empty string. This is not the preferred usage of implode() as glue would be the second parameter and thus, the bad prototype would be used.
- pieces
-
The array of strings to implode.
Return Values
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
ChangeLog
| Version | Description |
|---|---|
| 4.3.0 | The glue parameter became optional. |
Examples
Example #1 implode() example
<?php
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
?>
Notes
Note: This function is binary-safe.
implode
16-Aug-2008 03:51
30-Jul-2008 11:30
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
a - b - c - d - e - f - g - h
?>
25-Jul-2008 12:38
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>';
?>
23-Jul-2008 01:36
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;
}
?>
16-Jul-2008 02:47
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($output, 0, -strlen($glue));
}
?>
27-May-2008 02:12
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>
02-Apr-2008 12:36
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, "" ,0, strlen($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(",");
?>
18-Feb-2008 11:41
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_reverse( explode( ".", $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 );
}
?>
13-Jan-2008 04:00
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
09-Nov-2007 07:50
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.
10-Oct-2007 10:42
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
07-Oct-2007 12:42
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) ) < 1 )
{
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 ;)
09-Jul-2007 08:05
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($result, 0, strlen($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
04-Jul-2007 05:36
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);
}
02-Jul-2007 09:39
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);
14-Jun-2007 03:46
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.
20-Mar-2007 08:09
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
19-Mar-2007 10:52
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;
}
}
?>
04-Jan-2007 02:43
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
23-Nov-2006 02:33
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 (3 <= $count) {
$last = end($array);
$list = prev($array) . ($useOxfordComma ? ', and ' : ' and ') . $last;
while ($v = prev($array)) {
$list = $v . ', ' . $list;
}
} else if (2 == $count) {
$last = end($array);
$list = prev($array) . ' and ' . $last;
} else if (1 == $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.
23-Nov-2006 12:43
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($glue1, array_slice($array, 0, -2)).$glue1 : "").implode($glue2, array_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(', ', ' & ', $array)."<br />";
$array = array( 1, 2, 3, 4, 10);
echo "3: ".implode2(' + ', ' = ', $array)."<br />";
?>
This outputs
1: Monday and Tuesday
2: Mon, Tue, Wed, Thu & Fri
3: 1 + 2 + 3 + 4 = 10
05-Oct-2006 09:11
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 "&"
$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;
}
05-Sep-2006 09:18
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
12-Aug-2006 07: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);
}
}
?>
23-May-2006 04: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', '&'), 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&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' */
?>
03-Jan-2006 04: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);
}
31-Oct-2005 12: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'
27-Sep-2005 02: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
09-Sep-2005 04: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;
}
?>
29-Aug-2005 04: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));
}
?>
20-Aug-2005 01: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.
07-Jul-2005 07: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.
