How to use implode and explode in PHP

Implode and explode functions in PHP are commonly used function in PHP. These function may be used in PHP frameworks such as Laravel, CodeIgniter. Implode and explode functions are used to work with arrays and strings. So in this article i am going to explain how can can use Implode and Explode function in PHP.

Implode Function in PHP

The implode() function in PHP is used to join the items/elements of array or collection. This implode function return the string and we have to used a delimiter to join the array. These items of array will be joined by a delimiter such as ‘-‘. this hyphen will be join such as 5-86-87-5-2.

implode function in php takes input as an array and it joins the items of an array with a delimiter and returns the output in string format.

Lets suppose you write an array such as $num = Array ("52","85","2","8","6"); and if you use implode() function, it joins the array as following.
$out = implode("-",$num); and the output would be 52-85-2-8-6, You can use other delimiter s as well instead of hyphen.

Explode Function in PHP

The explode() function is used to split the string and it convert into pieces and these pieces can be converted into an array.
Lets suppose, I have a string as Ravindra Delhi India PHP and I want to use Ravindra as name, Delhi as city, India as country and PHP as programming. So I can split this string by space.

First, I need to define a string such as $str="Ravindra Delhi India PHP"; and now I need to use explode() function such as explode(" ",$str) and you can strong output into a string variable and it’s items can be accessed by index of array such as following.

$out=explode(” “,$str)
$out[0]=Ravindra
$out[1]=Delhi
$out[2]=India
$out[3]=PHP

If you want to print it with name and city as title, you can use as following.

Name : $out[0];
City : $out[1];
Country : $out[2];
Programming : $out[3];

The output will as following.

Name : Ravindra
City : Delhi
Country : India
Programming : PHP

Leave a Comment