Implode and Explode in PHP 7

This tutorial help to understand implode and explode differences underneath of php 7.The implode is used to join elements of an array with a string.The explode is used to split the string data into an array using delimiter string.

What’s Difference between explode() and implode()

The explode() function is used to breaks a string into an array,Whereas implode function returns a string from the elements of an array.

Create String from Array Using Implode() Method

We can create a string from an array using implode() method, its too simple and easy to use this function.We just need to pass two parameter, One is array of strings and second is a delimiter (string to be used between the pieces) of your response string.

The delimeter is used to joins them together into one string.

Syntax

implode (separator, array)

Let’s take an simple example –

$blog_arr = Array ("Hi,","I","am","phpflow","blog.");

Now, I ll combine above array using separator ' ' between each element of array.

$str = implode(" ",$blog_arr);

The results would be –

"Hi, I am phpflow blog."

The full source code –

<?php
 $blog_arr = Array ("Hi,","I","am","phpflow","blog.");
$str = implode(" ",$blog_arr);
 print_r($str);
 ?>

Split String in to array Using explode() Method

The explode() method is used to breaks a string into an array. You can split a string into chunks using separator.
The explode() and function breaks a string into an array, but the implode function returns a string from the elements of an array.

Syntax explode() Method

explode (separator,string,limit)

Let’s take an simple example –

$str = "Hi, I am phpflow blog.";

We want to split above string into pieces of string $str based on separator ' '.

$arr = explode(" ", $str);

The result would be :

Array
 (
     [0] => Hi,
     [1] => I
     [2] => am
     [3] => phpflow
     [4] => blog.
 )

Source Code of Explode()

The full source code of explode method in php.

$str = "Hi, I am phpflow blog.";

$arr = explode(" ", $str);

echo "";
print_r($arr);

Conclusion

This article help to understand the implode and explode functions in PHP. You can split string into array using explode() method, and vise-versa easily using implode() method.

Leave a Reply

Your email address will not be published.