PHP: Explode and Implode

I was a really late in discovering the explode and implode functions of PHP. Explode and Implode offer an extremely easy way to convert a delimited string into an array, and the exact reverse of that. Often times you will run into the situation where, in order to work with some specific data properly, or display it properly, you will need to convert it into a more usable format. I’ll give you a real-world example of each.

Example

In Magento (ecommerce platform), you can assign a product to any number of categories. In the database, these category IDs are stored in one column, separated by “/” and in order from smallest to largest (i.e. 6/13/38/50/81).

Let’s say that I need to write a script to put some specific products into a new category. We’ll say that new category has an ID of 20. If we need add category ID of 20 to this “6/13/38/50/81”, then we’ve got to be able to manipulate that string. So, in this example, we’ll be using explode() to get the data into a more usable format for inserting the new ID, and then using implode() to wrap it all up in the end.

Explode() will take string and convert it into an array, separating by whatever delimiter you give it. Implode() will take an array and convert it into a string, separated by any delimiter you want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$category_ids = "6/13/38/50/81";
$new_category = "20";
 
# Convert $category_ids into array
$ids = explode("/", $category_ids);
 
# Insert new category id into array
array_push($ids, $new_category);
 
# Sort array in numerical order
sort($ids);
 
# Convert array back to delimited string
$new_cat_string = implode("/", $ids);
 
echo $new_cat_string; // "6/13/20/38/50/81"

So, as you can see, we broke up the original category string into an array using explode(). With an array, it is very easy to put new values into it with the function array_push(). Then, we were easily able to sort it numerically with sort(). And finally, we can assemble the data back to it’s original form using implode().

This entry was posted in PHP. Bookmark the permalink.

Comments are closed.