Implode and Explode function in PHP, both are built-in functions and we use these functions to convert strings and array. Implode and Explode function in PHP are important function and both do the opposite work.
In this article we learn the following topics:
Implode function in PHP
Implode function in PHP is used to convert the array to strings. It takes an array and converts those array to strings by using any glue. The glue will be your choice.
Syntax:
1 | implode(Glue, Pieces) |
The implode function accept two parameters:
Glue: This parameter specifies a segment of the string that is used to join the pieces of the array together. This is an optional parameter with the default value being a blank string.
Pieces: This parameter accepts an array to create a final string.
Let’s take an example:
1 2 3 4 5 | <?php $names = array('John', 'Peter', 'Troposal'); $string = implode(", ", $names); echo $string; ?> |
Output: In the above code, the array has imploded by comma and space.
1 | John, Peter, Troposal |
Explode function in PHP
Explode function in PHP is used to convert string to an array. The explode function in PHP allows breaking a string into the smaller text at the same symbol with each break occurring. This symbol is called the Delimiter.
Syntax:
1 | explode(Delimiter, String) |
The explode function accept two parameters:
Delimiter: This parameter requires a segment of the string that can be used as a separator. It is a required parameter to explode function.
String: This parameter expects a string to explode.
1 2 3 4 5 | <?php $strings = 'Implode and Explode function in PHP'; $array = explode(" ", $strings); print_r($array); ?> |
Output: In the above example, the string has exploded by space(” “).
1 2 3 4 5 6 7 8 9 | Array ( [0] => Implode [1] => and [2] => Explode [3] => function [4] => in [5] => PHP ) |
Also, you can print array value by a loop in PHP
1 2 3 4 5 6 7 8 | <?php $strings = 'Implode and Explode function in PHP'; $array = explode(" ", $strings); foreach ($array as $value) { echo $value; echo "<br>"; } ?> |
Output:
1 2 3 4 5 6 | Implode and Explode function in PHP |
Difference between Implode and Explode function in PHP
Here is the Difference between Implode and Explode function in PHP in tabular form:
Implode function | Explode function |
---|---|
The implode function works on an array. | The explode function works on a string. |
The implode function returns string. | The explode function returns array. |
The first parameter of the implode function is optional. | The first parameter of the explode function is required. |