How to Break or Split String Into an Array Using PHP

Last Updated on May 25, 2021 by Roshan Parihar

In this tutorial, learn how to break or split a string into an array in PHP. The short answer is to use the explode() that returns an array after splitting the string.

There are many other methods you can also use to convert a string into an array. Let’s find out with the different examples given below here.

Method 1: Using Explode() to Split String Into an Array in PHP

To split a string into an array using PHP, you have to use the explode() function. It takes a two arguments in which the first is the space and the second is a string variable or string content.

Output

Array ( [0] => Welcome [1] => to [2] => TutorialDeep! )

The above example split the string using the explode() function to return an array. After that, it prints the array in the output using the print_r().

Method 2: Using preg_split() to Break String Into an Array Using PHP

When you want to break string content into an array, you can use the preg_split() function. It takes two arguments as showing in the example below. The second argument is the string variable or string content within double-quotes.

Output

Array ( [0] => Welcome [1] => to [2] => TutorialDeep! )

It returns the same output that is an array as you get in the previous example.

Method 3: Using For Loop

In addition to the above examples, you can also use the for loop of PHP. It is a little bit lengthy method that also uses the strlen() function to get the length of the string in PHP.

Output

Array ( [0] => Welcome [1] => to [2] => TutorialDeep! )

The output shows the same array as you get in the previous two examples.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.