Explode() is a widely-used PHP string function that is also one that tends to mystify beginners looking at others’ code. It’s a nifty little function that you may find plenty of uses for once you know how it works.
Explode() takes two arguments, a delimiter and the string you wish to operate on, then returns an array. The function splits a string into multiple pieces at the delimiter, and puts each piece into a numerical array.
Have a list of comma-separated words? (A scenario increasingly common now that “tagging” has become such a popular device.) You can pass a comma-delimited string to explode() with a delimiter of “,” and voila, you have an array containing each of the items.
$string = "lorem, ipsum, dolor";
$delimiter = ", ";
$array = explode($delimiter, $string);
Now you have a single-dimension numerical array with each list item in it.
$array would contain “lorem” and
$array would be “ipsum” and so on.
This is the easiest way to be able to extract parts of a string for use elsewhere in a script. As long as you have some idea of how the string will be formatted, you can explode() it and get the parts you want.
Need the domain of an email address, perhaps to check if the domain is on a blacklist of spammers? Try this:
$string = "firstname.lastname@example.org";
$delimiter = "@";
Now you have an array containing two parts, the user and the domain of the email. (
$array, respectively.) Now you can check the domain (microsoft.com) against your blacklist.
I’m sure there are plenty of scenarios where you would use this function. It’s used quite a lot, and for an amazingly wide variety of purposes. Try it out for yourself, you’ll need to use it sooner or later.