implode
(PHP 4, PHP 5)
implode — Join array elements with a string
Description
$glue
, array $pieces
)$pieces
)
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.
-
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
// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""
?>
Notes
Note: This function is binary-safe.
See Also
- explode() - Split a string by string
- preg_split() - Split string by a regular expression
- http_build_query() - Generate URL-encoded query string
- addcslashes
- addslashes
- bin2hex
- chop
- chr
- chunk_split
- convert_cyr_string
- convert_uudecode
- convert_uuencode
- count_chars
- crc32
- crypt
- echo
- explode
- fprintf
- get_html_translation_table
- hebrev
- hebrevc
- hex2bin
- html_entity_decode
- htmlentities
- htmlspecialchars_decode
- htmlspecialchars
- implode
- join
- lcfirst
- levenshtein
- localeconv
- ltrim
- md5_file
- md5
- metaphone
- money_format
- nl_langinfo
- nl2br
- number_format
- ord
- parse_str
- printf
- quoted_printable_decode
- quoted_printable_encode
- quotemeta
- rtrim
- setlocale
- sha1_file
- sha1
- similar_text
- soundex
- sprintf
- sscanf
- str_getcsv
- str_ireplace
- str_pad
- str_repeat
- str_replace
- str_rot13
- str_shuffle
- str_split
- str_word_count
- strcasecmp
- strchr
- strcmp
- strcoll
- strcspn
- strip_tags
- stripcslashes
- stripos
- stripslashes
- stristr
- strlen
- strnatcasecmp
- strnatcmp
- strncasecmp
- strncmp
- strpbrk
- strpos
- strrchr
- strrev
- strripos
- strrpos
- strspn
- strstr
- strtok
- strtolower
- strtoupper
- strtr
- substr_compare
- substr_count
- substr_replace
- substr
- trim
- ucfirst
- ucwords
- vfprintf
- vprintf
- vsprintf
- wordwrap
Коментарии
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: ''
If you want to implode an array of booleans, you will get a strange result:
<?php
var_dump(implode('',array(true, true, false, false, true)));
?>
Output:
string(3) "111"
TRUE became "1", FALSE became nothing.
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)"
?>
Be sure to escape/sanitize/use prepared statements if you get the ids from users.
It may be worth noting that if you accidentally call implode on a string rather than an array, you do NOT get your string back, you get NULL:
<?php
var_dump(implode(':', 'xxxxx'));
?>
returns
NULL
This threw me for a little while.
Can also be used for building tags or complex lists, like the following:
<?php
$elements = array('a', 'b', 'c');
echo "<ul><li>" . implode("</li><li>", $elements) . "</li></ul>";
?>
This is just an example, you can create a lot more just finding the right glue! ;)
null values are imploded too. You can use array_filter() to sort out null values.
<?php
$ar = array("hello", null, "world");
print(implode(',', $ar)); // hello,,world
print(implode(',', array_filter($ar, function($v){ return $v !== null; }))); // hello,world
?>
It might be worthwhile noting that the array supplied to implode() can contain objects, provided the objects implement the __toString() method.
Example:
<?php
class Foo
{
protected $title;
public function __construct($title)
{
$this->title = $title;
}
public function __toString()
{
return $this->title;
}
}
$array = [
new Foo('foo'),
new Foo('bar'),
new Foo('qux')
];
echo implode('; ', $array);
?>
will output:
foo; bar; qux
It's not obvious from the samples, if/how associative arrays are handled. The "implode" function acts on the array "values", disregarding any keys:
<?php
declare(strict_types=1);
$a = array( 'one','two','three' );
$b = array( '1st' => 'four', 'five', '3rd' => 'six' );
echo implode( ',', $a ),'/', implode( ',', $b );
?>
outputs:
one,two,three/four,five,six
If you want to implode an array as key-value pairs, this method comes in handy.
The third parameter is the symbol to be used between key and value.
<?php
function mapped_implode($glue, $array, $symbol = '=') {
return implode($glue, array_map(
function($k, $v) use($symbol) {
return $k . $symbol . $v;
},
array_keys($array),
array_values($array)
)
);
}
$arr = [
'x'=> 5,
'y'=> 7,
'z'=> 99,
'hello' => 'World',
7 => 'Foo',
];
echo mapped_implode(', ', $arr, ' is ');
// output: x is 5, y is 7, z is 99, hello is World, 7 is Foo
?>