Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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:

<?php
    $vegetables[0] = "corn";
    $vegetables[1] = "broccoli";
    $vegetables[2] = "zucchini";
    $text = implode(",", $vegetables);
    echo $text;
?>

This gives you:

corn,broccoli,zucchini

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

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

The result is:

corn, broccoli, zucchini

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:

<?php
    $text = "corn, broccoli, zucchini";
    $vegetables = explode(", ", $text);
    print_r($vegetables);
?>

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

Array
(
    [0] => corn
    [1] => broccoli
    [2] => zucchini
)
  • + Share This
  • 🔖 Save To Your Account