Understanding the Essentials of String to Array In PHP

PHP is an open-source language that is used for server-side development and scripting. It is widely known and used for server-side development. It works efficiently with databases like MySQL, Oracle, Microsoft SOL Server, PostgreSQL, and many other popular databases. It also supports file handling and data encryption. 

It supports a varied number of primitive data types in PHP. The 8 data types provided in PHP are categorized into 3 types namely, pre-defined or scalar type, compound type, and special type. This article gives an insight into the conversion of string data type to array in PHP and the advantages of achieving this.

Why Do You Need to Convert a String to an Array in PHP?

There are many cases when an array is considered more suitable over a string. For instance, you can convert the passwords entered as input in a web application into an array before storing them in the database. This provides more security and ease of access to the data. Arrays can help you implement better data organization and faster operations. When you convert a string into an array, it makes data manipulation convenient. Being a powerful scripting language, PHP provides various in-built methods to convert a string to an array. This article explains several approaches to achieve this task.

Following is the complete list of methods that can be used in PHP to convert a string to an array.

  1. str_split() Function
  2. explode("DELIMITER", STRING)
  3. preg_split() Function
  4. str_word_count() Function
  5. Manually loop through the string
  6. json_decode() Function
  7. unserialize() Function

Different Methods to Convert String to Array in PHP

There are various approaches, including in-built functions and manual approaches that are used to convert string to array in PHP. 

  • str_split() Function

The first method in this list is str_split(). This is an in-built PHP method that is used to convert a string into an array by breaking the string into smaller sub-strings of uniform length and storing them in an array. It does not use any kind of separator, it just splits the string.

The syntax of the str_split() function is:

str_split($initial_string, $splitting_length)

Parameters

  • $initial_string (mandatory): The first parameter you pass to this function is the string that has to be converted into an array.

  • $splitting_length (optional): The second parameter is an integer that represents how long the parts of the strings will be after splitting. It is an optional parameter. If not passed, the function will consider this length as 1 by default.

Return Value

This function returns an array that contains the pieces of the original string. If the length that is passed to the function surpasses the length of the initial string, the function will return the whole string as one element, whereas if the length integer is less than one, the function will return false.

Example

Input:

"Program"

Output:

Array

(

    [0] => P

    [1] => r

    [2] => o

    [3] => g

    [4] => r

    [5] => a

    [6] => m

)

Input:

"Programming Language"

Output:

Array

(

    [0] => Prog

    [1] => ram

    [2] => ming

    [3] => Lang

    [4] => uage

)

The following example illustrates the working of the str_split() function to convert string to array in PHP.

<?php

    // define a string

    $my_string = 'Sample String';   

    // without passing length

    // length = 1 (by default)

    $my_array1 = str_split($my_string);

    // print the array

    echo "The array of default length elements is: ";

    print_r($my_array1); // s, a, m, p, l, e, s, t, r, i, n, g

    print("<br><br>");   

    // passing length as second argument

    // length = 3

    $my_array2 = str_split($my_string, 3);

    // print the array

    echo "The array of length 3 elements is: ";

    print_r($my_array2); // sam, ple, str, ing 

?>

StringToArrayInPHP_1  

In the above example, it initializes a variable $my_string1 with a string “Sample String”. It uses the str_split() method to convert the string to an array. The following expression passes the string to this method without passing the length argument.

$my_array1 = str_split($my_string); 

By default, if you do not pass the length delimiter, it takes it as 1. So, it converts separate elements of the string into array elements. And the following expression passes 3 as the length delimiter, which converts the substring of length 3 into array elements.

$my_array2 = str_split($my_string, 3);

  • explode("DELIMITER", STRING);

The explode() function is another method of PHP that is used to convert a string into an array. Unlike the str_split() function, this function uses a separator or delimiter that needs to be passed as an argument to the function. This separator could be a comma (,), a dot (.), or anything. After splitting the string into smaller substrings, this function stores them in an array and returns the array.

The syntax of the explode() function is

explode($separator, $initial_string, $no_of_elements)

Parameters

  • $separator: The separator is a character that commands the explode() function to split the string whenever it detects the separator and stores that substring in the array.
  • $initial_name: The second parameter that is passed to this function is the string that has to be converted into an array.
  • $no_of_elements (optional): This is the last and an optional parameter that is passed to this function. This parameter represents the number of strings in which it should split the original string. This number can be positive, negative, or zero.
  • Positive: If the passed integer is positive, then the array will store this many numbers of elements. If you separate the string into more than N number of pieces regarding the delimiter, the first N-1 elements remain the same, and the rest of the elements combine to form a single element.
  • Zero: If the passed integer is 0, then the array will contain the whole string as a single element.
  • Negative: If the passed integer is negative then the last N elements of the array will be cut off and it will return the remaining elements. 

Return Value

The explode() function returns an array that contains the string pieces as its elements.

Example

Input:

explode(“ “, “Hello, what is your name?")

Output:

Array

(

    [0] => Hello,

    [1] => What

    [2] => is

    [3] => your

    [4] => name?

)

Input:

explode(“ “, “Hello, what is your name?", 3)

Output:

Array

(

    [0] => Hello,

    [1] => What

    [2] => is your name?

)

Input:

explode(“ “, “Hello, what is your name?", -1)

Output:

Array

(

    [0] => Hello,

    [1] => What

    [2] => is 

    [2] => your 

)

The following example illustrates the working of the explode() function to convert string to array in PHP.

<?php

    // define a string

    $my_string = 'red, green, blue';    

    // passing "," as the delimiter

    $my_array1 = explode(",", $my_string);

    // print the array

    echo "The converted Sarray is: <br>";

    print_r($my_array1); // red, green, blue 

?>

StringToArrayInPHP_2. 

In the above example, you are converting  a string containing three colors separated by a comma to an array. The comma “,”  is passed to the explode() function as a delimiter to convert the string into array elements.

  • preg_split() Function

The preg_split() is also an in-built PHP function that is used to convert a string into an array by splitting it into smaller substrings. Just like the explode() function, it also uses a separator but the separator in this function is a pattern of regular expressions. The length of substrings depends upon the integer value known as a limit that is passed to this function.

The syntax of the preg_split() function is :

preg_split($pattern, $string, $limit, $flags)

Parameters

  • $pattern: The pattern is a regular expression that determines what character is used as a separator to split the string.
  • $string: The second parameter that is passed to this function is the string that has to be converted into an array.
  • $limit (optional): The limit indicates the total number of substrings in which it will split the string. If all the separators appear before the limit ends, the (limit-1) elements remain the same and the rest of the elements combine to form the last element. If the limit is 0, then, it will return the whole string as one single element. However, it is an optional parameter. If not mentioned, it will consider the limit as -1 by default.
  • $flags (optional):  This is an optional parameter. If passed, it is used to bring some changes to the array. In other words, the flag represents the condition on which the final array will be returned. These options or conditions are:
    • PREG_SPLIT_NO_EMPTY: This flag type is used to remove the empty string and the non-empty strings will be returned.
    • PREG_SPLIT_DELIM_CAPTURE: This flag type is used to get the delimiter in the resulting array as well. If this flag is used, then the expression within the parenthesis will also be captured as an array element.
    • PREG_SPLIT_OFFSET_CAPTURE: This flag type makes the function return a pair as an array element. The first part of the pair will be the substring and the next part of the pair will be the index of the first character of the substring in the initial string.

Return Value

The preg_split() function returns an array containing the substrings as its elements, separated by the pattern passed to the function.

The following example illustrates the working of the preg_split() function to convert string to array in PHP.

<?php

    // define a string

    $my_string = 'hello';    

    // -1 -> no limit

    $my_array = preg_split('//', $my_string , -1, PREG_SPLIT_NO_EMPTY); 

    // print the array

    echo "The converted array is: <br>";

    print_r($my_array); // h, e, l, l, o

?>

StringToArrayInPHP_3

In the example depicted above, it converts the string “hello” into an array. It passes ‘-1’ as the limit argument, so there is no limit. The “//” is passed as the pattern to convert separate characters of the string into array elements. 

  • str_word_count() Function

The str_word_count() function is another in-built function. It is not used to split the string, but it gives information about the string, such as the number of characters in the string, and so on. 

The syntax of the str_word_count() function is:

str_word_count ( $string , $returnVal, $chars )

Parameters

  • $string: The first parameter that is passed to this function is the string that has to be converted into an array.
  • $returnVal (optional): This parameter indicates what the function will return. This is an optional parameter and by default, it is 0. It can take three different kinds of values:
      • 0: It is also the value by default. If the returnVal parameter is set to 0, then the function will return the total count of the number of words in the input string.
      • 1: If the returnVal parameter is set to 1, then the function will return an array containing all the words of the string as its elements.
  • 2: If you set if the returnVal parameter to 2, then the function will return an array containing the key-value pairs. The key will be the index of the word and the value will contain the word itself.
  • $chars (optional): This is again an optional parameter that tells the string to consider the character that is passed as a parameter to as a word as well. 

Return Value

The return value of the function depends on the parameters that are discussed above.

The following example illustrates the working of the str_word_count() function to convert string to array in PHP.

<?php

    // define a string

    $my_string = 'he2llo world';   

    // the character '2' will not be considered as word 

    $my_array1 = str_word_count($my_string, 1);

    // print the array

    echo "The converted array is: <br>";

    print_r($my_array1); // he, llo, world

    // the character '2' is passed as the third argument 

    $my_array2 = str_word_count($my_string, 1, 2); 

    // print the array

    echo "<br><br>The converted array is: <br>";

    print_r($my_array2); // he2llo, world 

?>

StringToArrayInPHP_4

In the above example, the string “he2llo world” contains a character ‘2’ which is not considered as a word by default by the function str_word_count(). So, the following expression converts the string into an array and ‘2’ is omitted.

$my_array1 = str_word_count($my_string, 1);

When you pass the character ‘2’ as the third argument to the str_count_world() function, then it is considered as a word and included in the array.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

  • Manually Loop Through the String

The next method in this list through which you can convert a string into an array is by manually looping through the string. You will initialize a variable, let's say “i”  as 0, and start a loop from ”i” until “i” becomes less than the length of the string. Inside the loop, you will store each word of the string in the array and increment the variable “i”.

The following example illustrates the manual approach using a for loop to convert string to array in PHP.

<?php

    // define a string

    $my_string = 'hello world';    

    // declare an empty array

    $my_array = [];

    // traverse the string

    for ($i = 0; $i < strlen($my_string); $i++) {

      if ($my_string[$i] != " ") { 

        $my_array[] = $my_string[$i]; 

      }        

    } 

    // print the array

    echo "The converted array is: <br>";

    print_r($my_array); // h, e, l, l, o, w, o, r, l, d 

?>

StringToArrayInPHP_5 

In the above example, an empty array is initialized. The string “hello world” is traversed using a for loop and each character of the string is inserted into the array.

  • json_decode() Function

The json_decode() function is used to decode a JSON encoded string. JSON stands for JavaScript Object Notation. JSON is a standard format for exchanging or transferring data and is powered by JavaScript. The JSON string usually represents the objects into data-value pairs.

The syntax of the json)decode() function is:  

json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 )

Parameters

  • $json: This parameter represents the JSON string that has to be encoded into an array.
  • $assoc: This parameter is of boolean data type. If it is true, then the function will convert the encoded string into an array.
  • $depth: It represents the depth of the recursion that will be used to decode the string.
  • $options (optional): It includes bitmasks of JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING,, JSON_THROW_ON_ERROR.

Return Value

This function returns the decoded JSON string. If the depth of the encoded string is deeper than the specified depth limit of the recursion, this function will simply return NULL.

The following example illustrates the working of the json_decode() function to convert string to array in PHP.

<?php

    // define a string

    $my_string = '{"h":2, "e":5, "l":4, "l":8, "o":10}';

   // convert into array

    $my_array = json_decode($my_string);

    // print the array

    echo "The converted array is: <br>";

    var_dump($my_array);  

?>

StringToArrayInPHP_6

In the above example, the string “hello” is initialized in the JSON format. The function json_decode() accepts this string as an argument, decodes it, and converts it into an array.

  • unserialize() Function

The unserialize() function is another in-built PHP function. It is just the opposite of the PHP serialize() function. This function converts a serialized string that is passed as a parameter, back into its original form i.e., an array.

The syntax of the unserialize() function is:

unserialize( $serialized_array, $options )

Parameters

  • $string: This parameter is the serialized string that needs to be unserialized.
  • $options (optional): This is an optional parameter that represents the options that can be provided to this function.

Return Value

The return value could be a boolean, string, integer, float, or anything.

The following example illustrates the working of the unserialize() function to convert string to array in PHP.

<?php

    // define a string

    $my_string = 'a:3:{i:0;s:1:"a";i:1;s:6:"sample";i:2;s:6:"string";}';

    // convert into array

    $my_array = unserialize($my_string);

    // print the array

    echo "The converted array is: <br>";

    print_r($my_array); 

?>

StringToArrayInPHP_7  

In the above example, a serialized string “ a sample string” is initialized. The unserialize() function accepts this string as an argument and unserializes this string and converts it back to the original array.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Final Thoughts!

To sum up quickly, in this article, you learned seven different methods to convert a string to an array of words in PHP. You started with a brief overview on PHP and understood the reasons why it is better to sometimes convert a string to an array. You learned the 7 different methods to convert the string to an array along with their description, syntax, return types, code, and output.

If you want to learn more of such important PHP concepts for beginners, you should check out Simplilearn’s PHP Training Course. This course is specially crafted for beginners by industry experts and will walk you through some fundamental concepts of PHP. By the end of this course, you will learn the fundamentals of PHP, advanced PHP development, how to build a CMS with PHP, create an image upload website, learn PHP MVC with MySQL, Object-oriented programming and data objects in PHP, and to build an efficient login system using PHP.

Already a PHP professional? No worries. Check out this course on Advanced PHP Development to skill yourself up and learn concepts such as cookies, sessions, etc. If you want to pursue a career in MEAN stack development (Mongo, Express, Angular, Node), you should check out our course on the Complete MEAN Stack Development Course. Here’s a list of completely free online courses that you should check out on Simplilearn. 

If you have any queries related to this article on “String to Array in PHP” or any suggestions, please drop a comment in the comment box and our experts will get back to you as soon as possible.

Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.