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
- Send an email using PHP mail() function
- Sorting Arrays in PHP
- Remove the last character from a string in PHP
- How to use session in 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.
Syntax:
explode([string delimiter],[string]);
Example:
<?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.
Syntax:
implode([string separator],[array]);
Example:
<?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 `, `.
<?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.
<?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!