Converting a String to an Array in PHP

Converting a String to an Array in PHP

When users submit form details like email, phone number, and name on a website, each input is typically processed and stored as part of an array. Arrays are often preferred in web development for handling user inputs, as they allow easier data manipulation, traversal, and element access. Operations like traversal, accessing specific elements, looping through data, and applying validation or transformations have a better time complexity on arrays than on strings.

As a web developer, you should make sure your website includes logic to convert form inputs into an array. In this article, we will explore various methods to convert a string into an array in PHP that you can add to your source code. If you are a PHP developer, this blog will be a handy reference for you.

Table of Contents:

What are PHP Strings?

Strings in PHP are a sequence of characters that are used to represent words or sentences, and are defined using single quotes (‘) and double quotes (). PHP strings are one of the most commonly used data types in PHP. They are used to store form inputs, passwords, email addresses, and more. Some examples of strings in PHP are:

  • Usernames: intellipaat_software123
  • Passwords: intellipaat#123
  • Email addresses: [email protected]
  • Error messages: “Error: password must contain alphanumeric digits.”
  • Website URLs: “https://www.intellipaat.com”
  • File paths: “C:\abc\htdocs\intellipaat\uploads\profile.jpg”
  • JSON strings: ‘{“city”:”Pune”, “pin”:”411001″, “state”:”Maharashtra”}’
  • HTML content: “<h1>Welcome!!!</h1>”
  • Session IDs: sess_bha12f8930a9edcc6b4d3a29f

What are PHP Arrays?

Arrays in PHP allow you to store multiple values under a single variable name. They are stored as ordered maps in memory. Unlike arrays in some other languages, PHP arrays are flexible and can hold elements of different data types at the same time. This makes managing related data easier using numeric or associative keys. 

  • Indexed Array: An Indexed array uses numeric indexing and starts from zero. 
    • For Example : [“Uttar Pradesh”, “Kerala”, “Gujarat”, “Punjab”]
  • Associative Array: An Associative array uses strings as keys and those keys are used for indexing.
    • For Example : [“name” => “Priya”, “age” => 20, “course” => “B.Sc”]
  • Multi-dimensional Array: Multidimensional array are nested arrays. Their elements are also arrays.
    • For Example : [“Delhi” => [“population” => 19000000, “state” => “Delhi”], “Mumbai” => [“population” => 20000000, “state” => “Maharashtra”]]

Why Convert a String to an Array in PHP?

Converting a string to an array in PHP helps make data easier to work with. It makes manipulating, accessing, and analyzing parts of a string efficient and faster. Some of the key reasons are:

  • When a string contains structured data like a list of names, words, or values, converting it into an array allows you to access and manipulate each part separately. For example, there is a scenario where you must extract a username from an email address. Removing it from a string can be difficult, but if you convert the string to an array, then it will be easily accessible using indexes.
  • An array makes it easy to loop through the data structures and access each element faster using for and foreach loops. 
  • In web development, strings received from forms or APIs are often separated by commas or some other delimiters like a semicolon (;) or an underscore (_). Converting them to arrays makes the data ready for storage, validation, or display.

How to Convert a PHP String to an Array?

There are various methods to convert a string to an array in PHP. These are built-in functions in PHP to carry out this task with ease. Let’s explore each method with practical examples.

1. Convert a String to an Array using PHP str_split()

The PHP str_split() method splits the whole string into substrings of equal length, where the length is provided by the developer. This function works on bytes, so if the string contains special or multibyte characters (like Hindi letters or emojis), it may not split them correctly. In such cases, use mb_str_split() instead.

Converts byte string to character array.

Syntax:

str_split ( $string , $length )

Parameters:

  • $string: This is the input string that is to be converted into an array.
  • $length: This is the length of the substring. If the user does not provide the length, PHP uses the default length of 1. 

Note: If the $length parameter provided is more than the length of the input string, then the whole string is returned as the first array element.

Example:

<?php
$string = "HelloWorld";
$array1 = str_split($string);
$array2 = str_split($string, 2);

echo "Default length:n";
print_r($array1);
echo "nLength = 2:n";
print_r($array2);
?>

Output:

Output - Convert a String to an Array in using PHP str_split()

Explanation: In this example, we convert the string “Hello” into an array using the str_split() function. In the first call, we didn’t specify the value for the $length parameter, so it took the default value of 1 and split the string into substrings of length one. In the next example, we specified a $length of 2 and it split the string into substrings of two characters each.

2. Convert a String to an Array in PHP using mb_str_split() 

The PHP mb_str_split() method is used to split a multibyte string (like those containing Hindi characters, emojis) into an array of characters. This method understands multibyte encodings like UTF-8, and hence, mb_str_split() handles special characters that the str_split() method cannot. 

Converts multi-byte string to character array.

Syntax:

mb_str_split ( $string , $length = 1 , $encoding = null )

Parameters:

  • $string: The input string to be split.
  • $length: It is an optional parameter that defines the length of each substring. The default value is 1.
  • $encoding: This is also an optional parameter. You can give the encoding of the input string. If not given, the internal encoding is used.

Note: mb_str_split() is available from PHP 7.4 and later.

Example:

<?php
$string = "हैलो🙂";
$array1 = mb_str_split($string);
$array2 = mb_str_split($string, 2);

echo "Default length:n";
print_r($array1);
echo "nLength = 2:n";
print_r($array2);
?>

Output:

Output - Convert a String to an Array in PHP using mb_str_split() 

Explanation: In this code example, in the first function call, the string “हैलो🙂” is split into individual characters. It correctly handles the multibyte string and the emoji. In the second function call, we set the length as 2, so it splits the string into substrings of two characters each.

Get 100% Hike!

Master Most in Demand Skills Now!

3. Convert a String to an Array in PHP using PHP explode()

The PHP explode function splits a string and converts it into an array, based on a delimiter like a comma, underscore, semicolon or dash. A delimiter can be any character you assign. It is useful when working with structured data like a CSV file. 

Splits a string by a custom delimiter.

Syntax:

explode ( $delimiter , $string , $limit )

Parameters:

  • $delimiter: This is the character at which the string will split.
  • $string: The input string to be split.
  • $limit: This is an optional parameter. $limit specifies the maximum number of elements in the resulting array.

Note: The delimiter in the explode function in PHP must be a string, not just a single character.

Example: Let us look at an example where we convert a comma-separated string into an array in PHP.

<?php
$string = "apple,mango,banana,grapes";
$array1 = explode(",", $string);
$array2 = explode(",", $string, 2);

echo "Without limit:n";
print_r($array1);
echo "nWith limit = 2:n";
print_r($array2);
?>

Output:

Output - Convert a String to an Array in PHP using PHP explode()

Explanation: In this example, we have a comma-separated string of fruit names. We used the explode function with a comma as the delimiter. In the first call, the comma-separated string was converted into an array. In the second call, the $limit was set as 2. Therefore, the string was split into only two parts.

4. Convert a String to an Array in PHP using preg_split() 

The preg_split function in PHP converts a string to an array based on a regular expression. This regular expression acts as a separator. It splits the string wherever a substring of the input matches the pattern of the given regular expression. 

Syntax:

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

Parameters:

  • $pattern: This is the regular expression used to split the string.
  • $string: This is the input string that is to be split.
  • $limit: This is an optional parameter that indicates the total number of substrings the string is supposed to be split into.
  • $flags: This is also an optional parameter. This decides how the results are supposed to be returned. The $flags parameter can take three values:
    • PREG_SPLIT_NO_EMPTY: Skips all the empty values in the result.
    • PREG_SPLIT_DELIM_CAPTURE: Includes the delimiters in the output array.
    • PREG_SPLIT_OFFSET_CAPTURE: Returns elements of the array along with the index where each part was found in the original string.

Note: Use // to enclose the pattern and to escape special characters.

Example:

<?php
$string = "apple,banana,,orange";
$result1 = preg_split("/,/", $string, -1, PREG_SPLIT_NO_EMPTY);

echo "Using PREG_SPLIT_NO_EMPTY:n";
print_r($result1);
echo "n";
$result2 = preg_split("/(,)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
echo "Using PREG_SPLIT_DELIM_CAPTURE:n";
print_r($result2);
echo "n";
$result3 = preg_split("/,/", $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
echo "Using PREG_SPLIT_OFFSET_CAPTURE:n";
print_r($result3);
?>

Output:

Output - Convert a String to an Array in PHP using preg_split() 1
Output Convert a String to an Array in PHP using preg split 2

Explanation: The string is split based on which the pattern is passed as the argument to the $pattern parameter. The double comma indicates a missing value between ‘banana’ and ‘orange’.

  • In the first function call, the PREG_SPLIT_NO_EMPTY flag was used. Therefore, it removed any empty strings in the output array.
  • In the second function call to convert a string to an array, the PREG_SPLIT_DELIM_CAPTURE flag was used. This saved the delimiter (,) in the output array.
  • In the final function call, the PREG_SPLIT_OFFSET_CAPTURE flag was used, which returned both the starting point and the substring element in the final output array. Apple started at 0, banana started at 6, and so on. The result is a nested array, with each element and its position. This helps in scenarios where knowing the position of each substring is important.

5. Convert a String to an Array in PHP using array_map() with str_split()

In PHP, the array_map function is used to apply a function to each element of an array. The array_map function, along with the str_split function, can be used to convert a string into an array in PHP.

Syntax:

array_map ( $callback , $array )

Parameters:

  • $callback: The function to apply. If you give the PHP str_split function as an argument to this parameter, it will convert a string to an array in PHP.
  • $array: An input array whose elements will be processed by the callback function.

Note: This method only works well with ASCII or single-byte characters. For multibyte strings, use mb_str_split() with a custom mapping logic.

Example:

<?php
$words = ["Hello", "Intellipaat"];
$charArrays = array_map('str_split', $words);
print_r($charArrays);
?>

Output:

Output - Convert a String to an Array in PHP using array_map() with str_split()

Explanation: In this example, we use array_map() to apply the str_split() function to each word in the $words array. The result is a multidimensional array where each string is converted into a character array. 

6. Convert a String to an Array in PHP using a Loop

If you want more control over how you want to split and convert a string to an array in PHP, you can simply create a loop. Using a loop in PHP, you can manually iterate over each character of the string and convert it into an array element.

You can define your function, and the syntax depends on the PHP loop you choose (for, foreach, etc.).

Example:

<?php
$string = "Intellipaat";
$array = [];
for ($i = 0; $i < strlen($string); $i++) {
    $array[] = $string[$i];
}
print_r($array);
?>

Output:

Output - Convert a String to an Array in PHP using a Loop

Explanation: In this example, we use a for loop to iterate over each character of the string and manually append it to the $array.

Which Method Should You Use to Convert a String to an Array in PHP?

Method Best For Handles Multibyte Encodings? Delimiter
str_split() Splitting ASCII strings into fixed-length chunks No No
mb_str_split() Splitting multibyte strings (e.g., emojis, Hindi) Yes No
explode() Splitting based on a specific delimiter (e.g., commas) No Yes
preg_split() Advanced splitting using regex patterns Yes Yes
array_map() + str_split() Splitting multiple strings into character arrays No No
Loop (for/foreach) Full custom logic, skipping or modifying characters No (or Yes with mb_str_split) Yes (manual)

Handling Special Characters and Encodings

When working with international text, emojis, or special symbols in PHP, some string functions may not work correctly. This is because these special characters use multibyte encodings. It is possible to handle multibyte string conversion to an array in PHP. There are many functions in PHP that handle multibyte characters and correctly interpret and process them. Instead of using the str_split function to split strings that contain multibyte characters, use the mb_str_split function of PHP. The mb_str_split is specifically designed to handle multibyte string conversion to an array in PHP.

Example:

<?php
$string = "नमस्ते🙂";
$array1 = str_split($string, 2);
$array2 = mb_str_split($string, 2);
echo "str_split function:n";
print_r($array1);
echo "nmb_str_split functionn";
print_r($array2);
?>

Output:

Output - Handling Special Characters and Encodings

Explanation: In the above example, str_split() fails to split the string to an array correctly, because it treats each byte separately, breaking multibyte characters. On the other hand, mb_str_split() handles multibyte characters like Hindi letters, emojis accurately and returns the proper character array. 

Conclusion

In this article, we have covered various methods and functions used to convert a string to an array in PHP, like explode(), str_split(), mb_str_split() and more. Understanding these methods will make data parsing and handling form inputs much more structured when used in your PHP projects. It is important that you choose a method based on the encoding of your input data and how you want it to be stored in the array. You should use parameters like $limit, $length or $flags to decide how you want to split the strings. Converting strings to arrays in PHP is a common but essential task in many web development scenarios.
If you are a PHP developer preparing for your next job role, mastering string-to-array conversion methods can give you an edge, as they appear quite often in the PHP interview questions.

Converting a String to an Array in PHP – FAQs

Q1. How to convert a string to an array?

You can convert a string to an array using functions like explode(), str_split(), or preg_split() in PHP, based on how you want to split it.

Q2. How do you break a string into an array in PHP?

You can break a string into an array using explode() for delimiters or str_split() to split by characters.

Q3. How to convert string to array in PHP without using explode function?

You can use str_split() to split by each character or preg_split() for pattern-based splitting without using explode().

Q4. What is explode in PHP with comma?

You can use explode(“,”, $string) to split a comma-separated string into an array of elements.

Q5. How to convert string to array in PHP?

You can use explode(), str_split(), or preg_split() depending on whether you’re splitting by delimiter, characters, or patterns.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner