PHP - Array implode
The PHP function implode operates on an array and is known as the "undo" function of explode.
If you have used explode to break up a string into chunks or just have
an array of stuff you can use implode to put them all into one string.
PHP implode - Repairing the Damage
The first argument of implode is the string of characters you want to use to join the
array pieces together. The second argument is the array (pieces).
PHP Code:
$pieces = array("Hello", "World,", "I", "am", "Here!");
$gluedTogetherSpaces = implode(" ", $pieces);
$gluedTogetherDashes = implode("-", $pieces);
for($i = 0; $i < count($pieces); $i++){
echo "Piece #$i = $pieces[$i] <br />";
}
echo "Glued with Spaces = $gluedTogetherSpaces <br />";
echo "Glued with Dashes = $gluedTogetherDashes";
Display:
Piece #0 = Hello
Piece #1 = World,
Piece #2 = I
Piece #3 = am
Piece #4 = Here!
Glued with Spaces = Hello World, I am Here!
Glued with Dashes = Hello-World,-I-am-Here!
The implode function will convert the entire array into a string and
there is no optional argument to limit this as there was in the explode function.
Download Tizag.com's PHP Book
If you would rather download the PDF of this tutorial, check out our
PHP eBook from the Tizag.com store.
Print it out, write all over it, post your favorite lessons all over your wall! Found Something Wrong in this Lesson?Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time! |