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.
$ARR = str_split($STR);
$ARR = explode("DELIMITER", $STR);
$ARR = preg_split("PATTERN", $STR);
$ARR = str_word_count($STR, 2);
- Manually loop through the string.
$ARR = [];
for ($i=0; $i<strlen($STR); $i++) { $ARR[] = $STR[$i]; }
$ARR = json_decode($STR);
$ARR = unserialize($STR);
But just how does each one of them work? Need more actual examples? Read on to find out!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
ARRAY TO STRING
All right, let us now get started with the various ways to convert a string to an array in PHP.
TUTORIAL VIDEO
1) SPLIT STRING
// (A) THE STRING
$str = "FOOBAR";
// (B) SPLIT STRING - SPLIT ALL CHARACTERS
$arr = str_split($str);
print_r($arr); // F, O, O, B, A, R
// (C) SET NUMBER OF CHARACTERS
$arr = str_split($str, 3);
print_r($arr); // 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
// (A) THE STRING
$str = "FOO-BAR";
// (B) SPLIT BY SPECIFIED CHARACTER
$arr = explode("-", $str);
print_r($arr); // 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
// (A) THE STRING
$str = "FOO BAR, HELLO WORLD";
// (B) SPLIT BY PATTERN
$arr = preg_split("/(\s|,\s)/", $str);
print_r($arr); // ["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
// (A) THE STRING
$str = "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($str, 0); // 8
// (B2) FORMAT 1 - RETURN ARRAY OF VALID WORDS
$arr = str_word_count($str, 1);
print_r($arr); // Foo, Bar, hello, world, Goodbye, world, John, Doe
// (B3) FORMAT 2 - RETURN ARRAY OF VALID WORDS, WITH STARTING POSTION
$arr = str_word_count($str, 2);
print_r($arr);
/* 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"
$arr = str_word_count($str, 2, "3@");
print_r($arr);
/* 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 as1
. 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
// (A) THE STRING
$str = "FOO-BAR";
// (B) MANUAL LOOP & SPLIT
$arr = [];
for ($i=0; $i<strlen($str); $i++) {
// YOUR CUSTOM RULES + PROCESSING
if ($str[$i] != "-") { $arr[] = $str[$i]; }
}
print_r($arr); // 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
// (A) JSON STRING
$str = '["Red","Green","Blue"]';
// (B) JSON DECODE
$arr = json_decode($str);
print_r($arr); // 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
// (A) SERIALIZED STRING
$str = 'a:3:{i:0;s:3:"Red";i:1;s:5:"Green";i:2;s:4:"Blue";}';
// (B) UNSERIALIZE BACK TO ARRAY
$arr = unserialize($str);
print_r($arr); // 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.
EXTRAS
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.
|
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
- Regular Expressions – PHP
- Convert Strings to Arrays in PHP – Dynamic Web Coding
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!