Site Admin
Site Admin Founder of MeaningArticles

PHP Convert String to Arrays Example

Hello Dev.

Converting a string into arrays in PHP is pretty straightforward. PHP offers various methods to convert string to arrays. We will have a look at explode and str_split built-in php functions. These methods split a string and convert it into arrays, let us check out the examples below:

1.Using PHP’s Explode Function

Let us begin with the PHP’s explode() function, this method takes 2 argument to convert string into array. The 1st argument takes the delimiter to explode the function, and the 2nd argument takes a string. To know more about php you can visit their official site here.

    $string = 'The Fountainhead, Dumbo, The Man Who Laughs, 7 Faces of Dr. Lao, Moulin Rouge';
    $movies_arr = explode(', ', $string);

/* Result:
array(5) {
  string(16) "The Fountainhead"
  string(5) "Dumbo"
  string(18) "The Man Who Laughs"
  string(18) "7 Faces of Dr. Lao"
  string(12) "Moulin Rouge"

2.Using PHP’s str_split Function to Convert String to Array

The str_split method also allows us to convert string to an array. The str_split function takes 2 arguments; in the first argument, we pass the string. In the second argument, we pass the number, and this number refers to an array element’s character length. By default, it is set to 1.

    $string = 'Loremipsumdolorsitamet';
    $string_split = str_split($string, 3);

/* Result:
array(8) {
  [0]=> string(3) "Lor"
  [1]=> string(3) "emi"
  [2]=> string(3) "psu"
  [3]=> string(3) "mdo"
  [4]=> string(3) "lor"
  [5]=> string(3) "sit"
  [6]=> string(3) "ame"
  [7]=> string(1) "t"

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.