Split string into an array with the explode() function in PHP

Have you ever needed to split a string into an array so that you can loop over it? Maybe its data from a text file or a CSV that you need to parse and read one by one? Then look no further, this article will explore the many ways to split strings into arrays.

Examples

You can split strings into an array using the PHP explode() function. The explode function is used in conjunction with a string and a delimiter. The delimiter is to instruct PHP where it should split the string and create array elements from. This function will quickly manipulate your small, medium, or large strings into a fully typed array.

Demonstration 1

First of all, let us define a string that we want to split into an array.

PHP

$myStringOfFoods = "Bacon, Eggs, Tomatoes, Potato, Broccoli, Bread, Milk, Pasta";

So, as you can see above, a comma-separated string has been defined. The commas have been used for the purposes of the tutorial but, in a real environment, this could be many other separators.

And now the working demonstration –

PHP

$myStringOfFoods = "Bacon, Eggs, Tomatoes, Potato, Broccoli, Bread, Milk, Pasta";

$myArrayOfFoods = explode(',', $myStringOfFoods);

In the above explode() function the first parameter (delimiter) is a comma and the second parameter (string) is the string we created earlier.

Output

array(8) { [0]=> string(5) "Bacon" [1]=> string(5) " Eggs" [2]=> string(9) " Tomatoes" [3]=> string(7) " Potato" [4]=> string(9) " Broccoli" [5]=> string(6) " Bread" [6]=> string(5) " Milk" [7]=> string(6) " Pasta" }

Method 2

For the second method, another style of string will be created to show the diversity of explode()

PHP

$myStringOfFoods = "Bacon! Eggs! Tomatoes! Potato! Broccoli! Bread! Milk! Pasta";

With the second string, each word has been ended with an exclamation mark, and therefore, this will be the delimiter to use when splitting the string.

Here’s the example with an exclamation mark delimiter using explode()

PHP

$myStringOfFoods = "Bacon! Eggs! Tomatoes! Potato! Broccoli! Bread! Milk! Pasta";

$myArrayOfFoods = explode('!', $myStringOfFoods);

In the above explode() function the first parameter (delimiter) is an exclamation mark and the second parameter (string) is the string we created with the new style delimiter.

Output

array(8) { [0]=> string(5) "Bacon" [1]=> string(5) " Eggs" [2]=> string(9) " Tomatoes" [3]=> string(7) " Potato" [4]=> string(9) " Broccoli" [5]=> string(6) " Bread" [6]=> string(5) " Milk" [7]=> string(6) " Pasta" }

And as you can see, the output is exactly the same. No matter what your delimiter, PHP will parse the string and convert it to an array.

If you want to read more on the explode() function, you can see the documentation here.

Posted in PHP

Leave a Reply