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

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): string

or

implode(array $array): string

(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,phone

Comparison 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()