Explode() and Implode() Function in PHP
Today we will explain to you how to use explode() and implode() function in PHP. When we need to convert string to array and array to string that time explode and implode functions are used in PHP.
Implode() and Explode() Function in PHP, Imploding and Exploding, Handling Strings and Arrays in PHP, PHP String Explode and Implode, What is the difference between implode() and explode() functions, convert array to string, convert string to array, Implode vs Explode in PHP.
Checkout more articles on PHP
1. explode() function
The explode()
function used to convert the string into array. It splits the string by the delimiter and returns an array.
1 | explode([string delimiter],[string]); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php $string = "Rose, Lotus, Sunflower, Marigold"; $flowers = explode(",",$string); print_r($flowers); ?> // Output: Array ( [0] => Rose [1] => Lotus [2] => Sunflower [3] => Marigold ) |
2. implode() function
The implode()
function used to convert the array into string. It joins the all elements of the array by separator and returns a string. Separator can be what you want to use to join the elements in string.
1 | implode([string separator],[array]); |
1 2 3 4 5 6 7 8 9 10 | <?php $flowers = ['Rose', 'Lotus', 'Sunflower', 'Marigold']; $string = implode(",",$flowers); print_r($string); ?> // Output: Rose,Lotus,Sunflower,Marigold |
To add space between elements in string we change the separator ,
to ,
.
1 2 3 4 5 6 7 8 9 10 | <?php $flowers = ['Rose', 'Lotus', 'Sunflower', 'Marigold']; $string = implode(", ",$flowers); print_r($string); ?> // Output: Rose, Lotus, Sunflower, Marigold |
If you want to join string using -
between elements of array.
1 2 3 4 5 6 7 8 9 10 | <?php $flowers = ['Rose', 'Lotus', 'Sunflower', 'Marigold']; $string = implode(" - ",$flowers); print_r($string); ?> // Output: Rose - Lotus - Sunflower - Marigold |
That’s it for today.
Thanks for reading. Happy Coding!