implode vs explode in php

Implode vs Explode in PHP

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.

Implode()

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)

Syntax

string implode ( string $glue , array $pieces )

Example:


$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.

Explode()

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

Syntax

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

Example:

$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.


<?php
if(isset($_POST['submit'])){
$input = $_POST['num'];
$ctr = 1;
while ($ctr <= $input) {
$array[$ctr] = $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">
</form>

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.


<?php
if(isset($_POST['str'])){
$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">
</form>

Leave a Reply

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