• support@answerspoint.com

Handling Strings and Arrays in PHP

Imploding and Exploding Arrays

You can also convert between strings and arrays by using the PHP implode and explode functions: implode implodes an array to a string, and explode explodes a string into an array.

For example, say you want to put an array's contents into a string. You can use implode, passing it the text you want to separate each element with in the output string (in this example, we use a comma) and the array to work on:

    $colors[0] = "red";
    $colors[1] = "green";
    $colors[2] = "white";
    $text = implode(",", $colors);
    echo $text;

This gives you:


There are no spaces between the items in this string, however, so we change the separator string from "," to ", ":

$text = implode(", ", $colors);

The result is:

red, green, white

What about exploding a string into an array? To do that, you indicate the text that you want to split the string on, such as ", ", and pass that to explode. Here's an example:

    $text = "red, green, white";
    $colors = explode(", ", $text);

And here are the results. As you can see, we exploded the string into an array correctly:

    [0] => red
    [1] => green
    [2] => white


    Facebook Share        
  • asked 5 years ago
  • viewed 1205 times
  • active 5 years ago

Top Rated Blogs