If you are just getting started in PHP, you need to know about the PHP explode (and PHP implode) functions. They are two of the most useful utility functions built into PHP for manipulating strings.
array explode ( string $delimiter , string $string [, int $limit ] )
When the $delimiter is found in $string, everything in $string up to that point is put into the first element of the return array. Subsequent found delimiters in $string behave the same, effectively creating an array of string pieces.
For example, this function would be very useful for consuming a comma separated list. Given the following list:
$string = "apple, banana, pineapple, grape, orange";
We can split this list into an array of fruits:
$fruits = explode(", ", $string);
The resulting array would look like:
["apple", "banana", "pineapple", "grape", "orange"]
The function will find every instance of ", " and split the string into an array for easy manipulating later in the code. Explode can also be used like the Linux command line tool grep for finding specific things in strings by parsing out the pieces you don't need.
Implode, on the other hand, works in the opposite direction — it takes an array and combines it into a string based on a delimiter.
string implode ( string $glue , array $pieces )
The combination of explode and implode works well for data manipulation. Let's look at our previous fruit example. We've already read in the comma separated list to get our fruits array. Now, let's transform this data into a structure that our back end system needs for a proper import (which, in this case, needs a pipe separated list).
To do this, we just need to call implode using the | character as our glue.
$fruitString = implode("|", $fruit);
That's it. Implode will happily smash our $fruit array into the following string:
The PHP Explode and Implode functions are both powerful tools to have in your back pocket when developing applications. They can save you a lot of time, lines of code, and unnecessary looping if used correctly. The real fun starts when you start chaining explode calls to continue to split strings that have already been split, but I'll leave you to experiment with that on your own.