- Listing of String Functions
- Using the String Functions
- Formatting Strings
- Converting to and from Strings
- Creating Arrays
- Modifying Arrays
- Removing Array Elements
- Looping Over Arrays
- Listing of the Array Functions
- Sorting Arrays
- Navigating through Arrays
- Imploding and Exploding Arrays
- Extracting Variables from Arrays
- Merging and Splitting Arrays
- Comparing Arrays
- Manipulating the Data in Arrays
- Creating Multidimensional Arrays
- Looping Over Multidimensional Arrays
- Using the Array Operators
- Summary
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 )