7 Ways To Convert String To Array In PHP

Welcome to a beginner’s tutorial on how to convert a string to an array in PHP. So you need to convert a string of data into an array before you can do your magic.

There are a couple of ways to convert a string to an array in PHP.

  1. $array = str_split(STRING);
  2. $array = explode("DELIMITER", STRING);
  3. $split = preg_split("PATTERN", STRING);
  4. $array = str_word_count(STRING, 2);
  5. Manually loop through the string.
    • $array = [];
    • for ($i=0; $i<strlen(STRING); $i++) { $array[] = STRING[$i]; }
  6. $array = json_decode(ENCODED STRING);
  7. $array = unserialize(SERIALIZED STRING);

But just how does each one of them work? Need more actual examples? Read on to find out!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

QUICK SLIDES

 

 

TABLE OF CONTENTS

Download & Notes String To Array Useful Bits & Links
Tutorial Video What’s Next?

 

 

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

ARRAY TO STRING

All right, let us now get started with the various ways to convert a string to an array in PHP.

 

1) SPLIT STRING

1-split-string.php
// (A) THE STRING
$thestring = "FOOBAR";
 
// (B) SPLIT STRING - SPLIT ALL CHARACTERS
$thearray = str_split($thestring);
print_r($thearray); // F, O, O, B, A, R
 
// (C) SET NUMBER OF CHARACTERS
$thearray = str_split($thestring, 3);
print_r($thearray); // FOO, BAR

This should be pretty self-explanatory. The str_split() function simply “breaks” the individual characters in a string down, and puts them into an array. Yes, we can also specify the number of characters to pull from the string.

 

 

2) EXPLODE FUNCTION

2-explode.php
// (A) THE STRING
$thestring = "FOO-BAR";
 
// (B) SPLIT BY SPECIFIED CHARACTER
$thearray = explode("-", $thestring);
print_r($thearray); // FOO, BAR

The explode() function is the cousin of str_split(). But instead of breaking a string by the number of characters, it breaks the string by a given DELIMITER character (or characters).

 

3) PREG SPLIT

3-preg-split.php
// (A) THE STRING
$thestring = "FOO BAR, HELLO WORLD";
 
// (B) SPLIT BY PATTERN
$thearray = preg_split("/(\s|,\s)/", $thestring);
print_r($thearray); // ["FOO", "BAR", "HELLO", "WORLD"]

So what happens if we have VERY specific instructions on how to break a string? Introducing, the preg_split() function, where we can specify a custom rule on how to break the string into an array. In the above example, the /(\s|,\s)/ part is called a regular expression. In English, it reads “a white space \s, or | a comma followed by white space ,\s“.

Yep, even though the regular expression is flexible and powerful, it is also “inhuman” and difficult to understand at the same time. As it is a can of worms on its own, I will just leave a link below for those of you who want to learn more.

 

 

4) STRING WORD COUNT

4-str-word-count.php
// (A) THE STRING
$thestring = "Foo Bar, hello world. Goodbye world3 = John@Doe.";
 
// (B) STR_WORD_COUNT(STRING, FORMAT, LIST)
// (B1) FORMAT 0 - RETURNS NUMBER OF VALID WORDS
echo str_word_count($thestring, 0); // 8
 
// (B2) FORMAT 1 - RETURN ARRAY OF VALID WORDS
$thearray = str_word_count($thestring, 1);
print_r($thearray); // Foo, Bar, hello, world, Goodbye, world, John, Doe
 
// (B3) FORMAT 2 - RETURN ARRAY OF VALID WORDS, WITH STARTING POSTION
$thearray = str_word_count($thestring, 2);
print_r($thearray); 
/* 0 - Foo,
 * 4 - Bar,
 * 9 - hello,
 * 15 - world,
 * 22 - Goodbye,
 * 30 - world,
 * 39 - John,
 * 44 - Doe
 */

// (C) 3RD PARAMETER - CHARACTERS TO CONSIDER AS "ENGLISH WORD"
$thearray = str_word_count($thestring, 2, "3@");
print_r($thearray); 
/* 0 - Foo,
 * 4 - Bar,
 * 9 - hello,
 * 15 - world,
 * 22 - Goodbye,
 * 30 - world3,
 * 39 - John@Doe
 */

What!? Word count? Yes, the str_word_count() may not seem like a function that is used to convert a string to an array, but it is… At least for 2 out of 3 of its possible “modes”.

  • Kind of confusing, but str_word_count(STRING, MODE, LIST) takes in 3 parameters.
  • The first parameter is the STRING itself. Captain Obvious. 🙄
  • The second parameter is the important one that “changes” the MODE of the function.
    • 0 will simply count the total number of valid English words in the string. Not what we are looking for.
    • 1 will return an array of valid words in the string – Yes, this is useful if you want to filter out all the gibberish in a string.
    • 2 does the same as 1. But the index of the array will correspond to the starting position of the word in the string.
  • Finally, the last LIST parameter is optional – We can use this one to override and tell PHP to accept this list of characters as “valid English word”.

 

5) MANUAL FOR LOOP

5-manual.php
// (A) THE STRING
$thestring = "FOO-BAR";
 
// (B) MANUAL LOOP & SPLIT
$thearray = [];
for ($i=0; $i<strlen($thestring); $i++) {
  // YOUR CUSTOM RULES + PROCESSING
  if ($thestring[$i] != "-") { $thearray[] = $thestring[$i]; }
}
print_r($thearray); // F, O, O, B, A, R

Finally, here is a “manual” alternative – We simply use a for loop to run through the characters of a string. Yep, the characters of a string act just like an array, and we can access them via STRING[N]. While this may seem to be quite a hassle, but the good part is – We can do all sorts of “special” rules and processing with this one.

 

 

6) JSON DECODE

6-json.php
// (A) JSON STRING
$thestring = '["Red","Green","Blue"]';
 
// (B) JSON DECODE
$thearray = json_decode($thestring);
print_r($thearray); // Red, Green, Blue

The json_decode(STRING) function takes a (previously) JSON encoded string, and turns it back into an array (or object). Yes, for you guys who have not heard, JSON stands for Javascript Object Notation. In simple terms, it’s a great way to JSON encode an array in Javascript, send it to the server, then JSON decode in PHP to get the array back.

 

7) UNSERIALIZE

7-unserialize.php
// (A) SERIALIZED STRING
$thestring = 'a:3:{i:0;s:3:"Red";i:1;s:5:"Green";i:2;s:4:"Blue";}';
 
// (B) UNSERIALIZE BACK TO ARRAY
$thearray = unserialize($thestring);
print_r($thearray); // Red, Green, Blue

For you guys who have not heard – Yes, we can store arrays, objects, functions, and almost anything as serialized strings in PHP using the serialize() function. To get it back, we simply use the unserialize() function.

 

 

USEFUL BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

SUMMARY

Function Description Reference Link
str_split(STRING, CHARACTERS) Split the characters of the given string into an array. Click Here
explode(DELIMITER, STRING) Split the given string into an array, separated by the given DELIMITER. Click Here
preg_split(EXPRESSION, STRING) Split the given string into an array by the given regular expression. Click Here
str_word_count(STRING, FORMAT, LIST) Kind of a multi-purpose tool.

  • STRING is the string itself to work on…
  • FORMAT
    • 0 to return the number of words in the string.
    • 1 returns an array of words found in the string.
    • 2 to return an array of words, but the key will also mark the starting position of the word.
  • LIST is optional, a list of special characters to also consider as “an English word”.
Click Here
json_decode(STRING) Turns a JSON encoded string back into an array. Click Here
unserialize(STRING) Turns a serialized string back into an array, object, function, or whatever it used to be in PHP. Click Here

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

Convert String To Array In PHP (Click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

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