2081 12

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]

Web Technology IIChapter 5: String Processing and Regular ExpressionsString exploding and imploding

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

Featureexplode()implode()
PurposeSplits a string into an arrayJoins an array into a string
InputStringArray
OutputArrayString
Also known asSplitJoin

Key Point: explode() and implode() 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.