BIT301 ยท 2081 ยท 5 marks
What is exploding and imploding of strings? Illustrate with an example.
What is exploding and imploding of strings? Illustrate with an example. [5]
Quick answer
Exploding means splitting a string into an array based on a specified delimiter/separator. In PHP, this is done using the built-in explode() function.
Exploding and Imploding of Strings in PHP
1. Exploding a String
Syntax:
explode(separator, string, limit)
separator- the delimiter used to split the string (required)string- the input string to be split (required)limit- maximum number of elements in the array (optional)
Example:
<?php
$str = "Apple,Banana,Mango,Orange";
$fruits = explode(",", $str);
print_r($fruits);
?>
Output:
Array
(
[0] => Apple
[1] => Banana
[2] => Mango
[3] => Orange
)
Here, the string is split at every comma , and each part becomes an element of the array.
2. Imploding a String
Imploding means joining array elements into a single string using a specified separator/glue. In PHP, this is done using the built-in implode() function (also called join()).
Syntax:
implode(separator, array)
separator- the string placed between each array element (required)array- the array whose elements are to be joined (required)
Example:
<?php
$fruits = array("Apple", "Banana", "Mango", "Orange");
$str = implode(" - ", $fruits);
echo $str;
?>
Output:
Apple - Banana - Mango - Orange
Here, the array elements are joined together with - as the separator to form a single string.
Summary Table
| Feature | explode() | implode() |
|---|---|---|
| Purpose | Splits a string into an array | Joins an array into a string |
| Input | String | Array |
| Output | Array | String |
| Also known as | Split | Join |
Key Point:
explode()andimplode()are inverse operations of each other. Explode breaks a string apart; implode brings array pieces together.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.