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.
- $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 = json_decode($STR);
- $ARR = unserialize($STR);
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.
TLDR – QUICK SLIDES
TABLE OF CONTENTS
DOWNLOAD & NOTES
First, here is the download link to the example source code as promised.
QUICK NOTES
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
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
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
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
- 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.
5) MANUAL FOR LOOP
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
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
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.
EXTRA 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
- 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.
LINKS & REFERENCES
-
– PHP – Dynamic Web Coding
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET
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 Cancel Reply
Search
report this ad
Breakthrough Javascript

Take pictures with the webcam? Voice commands? Video calls? Yes, it is possible with Javascript — Check out Breakthrough Javascript!
how to convert a string to an array in php [duplicate]
The str_split($str, 3); splits the string in 3 character word but I need to convert the string after whitespace in an array.

10 Answers 10
The first argument is delimiter

With explode function of php
This is a quick example for you http://codepad.org/Pbg4n76i

try json_decode like so

Take a look at the explode function.
There is a function in PHP specifically designed for that purpose, str_word_count() . By default it does not take into account the numbers and multibyte characters, but they can be added as a list of additional characters in the charlist parameter. Charlist parameter also accepts a range of characters as in the example.
One benefit of this function over explode() is that the punctuation marks, spaces and new lines are avoided.
implode
Alternative signature (not supported with named arguments):
Legacy signature (deprecated as of PHP 7.4.0, removed as of PHP 8.0.0):
Join array elements with a separator string.
Parameters
Optional. Defaults to an empty string.
The array of strings to implode.
Return Values
Returns a string containing a string representation of all the array elements in the same order, with the separator string between each element.
Changelog
Version Description 8.0.0 Passing the separator after the array is no longer supported. 7.4.0 Passing the separator after the array (i.e. using the legacy signature) has been deprecated. Examples
Example #1 implode() example
$array = [ ‘lastname’ , ’email’ , ‘phone’ ];
var_dump ( implode ( «,» , $array )); // string(20) «lastname,email,phone»// Empty string when using an empty array:
var_dump ( implode ( ‘hello’ , [])); // string(0) «»// The separator is optional:
var_dump ( implode ([ ‘a’ , ‘b’ , ‘c’ ])); // string(3) «abc»Notes
Note: This function is binary-safe.
See Also
- explode() — Split a string by a string
- preg_split() — Split string by a regular expression
- http_build_query() — Generate URL-encoded query string
User Contributed Notes 14 notes
it should be noted that an array with one or no elements works fine. for example:
<?php
$a1 = array( «1» , «2» , «3» );
$a2 = array( «a» );
$a3 = array();echo «a1 is: ‘» . implode ( «‘,'» , $a1 ). «‘<br>» ;
echo «a2 is: ‘» . implode ( «‘,'» , $a2 ). «‘<br>» ;
echo «a3 is: ‘» . implode ( «‘,'» , $a3 ). «‘<br>» ;
?>will produce:
===========
a1 is: ‘1’,’2′,’3′
a2 is: ‘a’
a3 is: »It’s not obvious from the samples, if/how associative arrays are handled. The «implode» function acts on the array «values», disregarding any keys:
<?php
declare( strict_types = 1 );$a = array( ‘one’ , ‘two’ , ‘three’ );
$b = array( ‘1st’ => ‘four’ , ‘five’ , ‘3rd’ => ‘six’ );echo implode ( ‘,’ , $a ), ‘/’ , implode ( ‘,’ , $b );
?>outputs:
one,two,three/four,five,sixSometimes it’s necessary to add a string not just between the items, but before or after too, and proper handling of zero items is also needed.
In this case, simply prepending/appending the separator next to implode() is not enough, so I made this little helper function.function wrap_implode ( $array , $before = » , $after = » , $separator = » ) <
if( ! $array ) return » ;
return $before . implode ( » < $after >< $separator > < $before >» , $array ) . $after ;
>echo wrap_implode ([ ‘path’ , ‘to’ , ‘file.php’ ], ‘/’ );
// «/path/to/file.php»$pattern = ‘#’ . wrap_implode ([ 4 , 2 , 2 ], ‘\d<' , '>‘ , ‘[-.]’ ) . ‘#’ ;
echo $pattern , «\n» ; // #\d<4>[-.]\d<2>[-.]\d<2>#
echo preg_replace ( $pattern , ‘[REDACTED]’ , ‘The UFO appeared between 2012-12-24 and 2013.01.06 every night.’ );
// ‘The UFO appeared between [REDACTED] and [REDACTED] every night.Преобразование строк в массив и наоборот на PHP

Как преобразовать на php массив в строку с разделителями?
В разработке сайтов на PHP часто нужно сделать из массива строку разделенную например запятыми, в основном такие строки используются для формирования JS кода на PHP
Для в php существует функция implode которая объединяет элементы простого одномерного массива в строку с разделителями указанными в 1-м параметре функции implode
implode($separate, $array)
implode — возвращает строку, полученную путем объединения строковых элементов массива $array, со вставкой строки $separate между соседними элементами.
Функция implode безопасна для обработки данных в двоичной форме.
Пример работы implode:
php implode для вложенных массивов
Если передать в функцию implode в качестве параметра многомерный массив, то результат выдаст ошибку «Array to string conversion». Чтобы избежать такой ситуации используйте решение для функции implode в виде рекурсивного вызова
Также в обратном порядке преобразовать строку с разделителями в массим можно функцией explode, которая возвращает одномерный массив, полученный путем разбиения строки по указанному разделителю