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.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare string $myStr = "Welcome to TutorialDeep!"; //Break string to array $StrtoArrr = explode(" ",$myStr) //Print result print_r($StrtoArrr); ?> |
Output
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.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare string $myStr = "Welcome to TutorialDeep!"; //Split string to array $StrtoArrr = preg_split("/ /", $myStr); //Print result print_r($StrtoArrr); ?> |
Output
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php //Declare string $myStr = "Welcome to TutorialDeep!"; //Break string to array $StrtoArrr =array(); $word = ""; for($i=0;$i<strlen($myStr);$i++){ if($myStr[$i] == " "){ $StrtoArrr[] = $word; $word = ""; } else{ $word .= $myStr[$i]; } } // for last word if($word != ''){ $StrtoArrr[] = $word; } //Print result print_r($StrtoArrr); ?> |
Output
The output shows the same array as you get in the previous two examples.
You May Also Like to Read