Implode vs Explode in PHP

by Sam  

As we know, a variable serves as a “container” that holds a value.  It has many types like integer, string, boolean, etc. On the other hand, an array is a special type of variable that holds multiple value at the same time.

To display the string value of a variable, we use echo. However, we cannot echo out the variable if it’s in an array format since it returns an error. Now, how are we going to solve it? And, how are we going to convert $str into an array? In this case, we need to use explode and implode functions respectively.


Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element. (From Array to String)


string implode ( string $glue , array $pieces )


$names = ['Sam', 'John', 'James'];
echo implode(',', $names); //displays Sam,John,James

From the example above, we converted an array to string and concatenated with comma(,) as a glue.


Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter (From String to Array).


explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )


$str = "What is your name?";
$array = explode('  ', $str); // Array ( [0] => What [1] => is [2] => your [3] => name? )

Explode is very useful if you want to get a character or a word from a given string. Example, if you want to get the first word, you can add, echo $array[0]; in order to display “What” word.

Explode and Implode Exercises with PHP Form

Implode Exercise.

Create a PHP script that will accept an integer and display the list of  series number from 1 until the input number.

$input = $_POST['num'];
$ctr = 1;
while ($ctr <= $input) {
$array[$ctr] = $ctr;
echo "Output: " . implode(",", $array);
<form action="" method="POST">
<label>Enter a number</label>
<input type="text" name="num">
<input type="submit" name="submit" value="Submit">

You may also check on some of our exercises below:
Implode in Multiple Array PHP
Implode in Laravel Blade

Explode Exercise.

Create a PHP script that will accept a string from the user and display the last word entered.

$str = $_POST['str'];
$array = explode(' ', $str);
$count = count($array);
echo "The last word is : " . $array[$count - 1];
<form action="" method="POST">
<label>Enter a string</label>
<input type="text" name="str">
<input type="submit" name="submit" value="Submit">

Leave a Reply

Your email address will not be published. Required fields are marked *

Need of a Website?

Maybe you're planning to build a landing page for your website. You might also have a plan to create a web application. I can offer you with an affordable but with good quality services. Don't hesitate to submit your specifications by clicking the button below.

Get Quote