Skip to content

PHP Explode Tips and Tricks

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.

Before we dive into some examples, we have just a bit of history to cover. As you are probably learning, PHP has quite a few built-in functions that do various things, and some that overlap. The PHP explode function is one such that shares functionality with the split function. JavaScript also contains a split function, and this is where I suspect PHP’s split came from. However, split in PHP has been deprecated since version 5.3.0 in favor of “explode”, so you should use explode in any ongoing development.

Much like the JavaScript counterpart split, the PHP explode function takes a string and splits it into an array based on a delimiter. The usage is simple:

When the $delimiter is found in “$string”, everything in $string up to that point is put into the first element of the return array. Subsequently 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:

We can split this list into an array of fruits:

The resulting array would look like:

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 as 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.

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.

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.


Published inBlogPHP