Difference Between Explode and Implode in PHP
In PHP development, string and array manipulation are fundamental
tasks. This article explains the key differences between the
explode() and implode() functions, detailing
how they convert data between strings and arrays, their respective
syntaxes, and how to use them with practical code examples.
Key Difference at a Glance
The fundamental difference lies in the direction of the data
conversion: * explode() splits a single
string into an array of smaller
strings based on a defined delimiter. *
implode() joins the elements of an
array into a single string, gluing
them together with a defined separator.
The explode() Function
The explode() function breaks a string into an array.
PHP looks for a specific delimiter (separator) within the target string
and splits the string at every occurrence of that delimiter.
Syntax
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array$separator: The character or string marking where to split the input string. This cannot be an empty string"".$string: The input string to be split.$limit(Optional):- If positive, the returned array will contain a maximum of
$limitelements, with the last element containing the rest of the string. - If negative, all components except the last
-$limitelements are returned. - If zero, it is treated as 1.
- If positive, the returned array will contain a maximum of
Example
$pizza = "piece1,piece2,piece3";
$pieces = explode(",", $pizza);
print_r($pieces);
/* Output:
Array
(
[0] => piece1
[1] => piece2
[2] => piece3
)
*/The implode() Function
The implode() function (which also has an alias called
join()) takes the elements of an array and concatenates
them into a single string.
Syntax
implode(string $separator, array $array): stringor
implode(array $array): string$separator(Optional): The string placed between the array elements. Defaults to an empty string"".$array: The array of strings to be joined.
(Note: While the separator parameter was historically optional, passing it is highly recommended for code readability and consistency across different PHP versions.)
Example
$array = ['lastname', 'email', 'phone'];
$comma_separated = implode(",", $array);
echo $comma_separated;
// Output: lastname,email,phoneComparison of Features
| Feature | explode() |
implode() |
|---|---|---|
| Primary Purpose | Splits a string into an array | Joins array elements into a string |
| Input Type | String | Array |
| Output Type | Array | String |
| Delimiter Dependency | Delimiter is mandatory | Delimiter is optional (defaults to
"") |
| Alias | None | join() |