Sunday, June 19, 2016

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!
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.