Converting a String to an Array in PHP

Converting-string-to-array-in-PHP-feature-image.jpg

In PHP, converting a string to an array is a common way for handling form input like names, emails, or phone numbers. The explode function is often used to split a string into parts based on a separator (like a comma or space). This makes form input parsing easier, as arrays let you loop through, validate, and manage data more efficiently than raw strings.

As a web developer, you should make sure your website includes logic to convert string to array in PHP. In this article, we will explore various string conversion methods 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 arrays 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 string to array in PHP helps make data easier to work with. It makes manipulating, accessing, and analyzing parts of a string efficient and faster. This aspect of PHP string manipulation is fundamental. 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 string conversion methods to convert string to array in PHP. These are built-in functions in PHP to carry out this task with ease. Let’s explore these string conversion methods in PHP 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 to convert a multibyte string to array in PHP

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 or 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. It is specifically designed to convert a multibyte string to array in PHP.

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.

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 to 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 string to 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. This offers advanced PHP string manipulation capabilities.

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 string to array in PHP, 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 string into 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 string to 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 to convert multibyte string to array in PHP

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 string to 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. This is also one of the string conversion methods in PHP.

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 and emojis accurately and returns the proper character array. 

Best Practices for Choosing PHP String Split Functions

  • You must use explode() for simple splits when you have a clear delimiter like commas or spaces and need an array of substrings.
  • You can use str_split() for fixed-length splits when you need to break a string into equal parts, like splitting every 2 characters. This is good practice in PHP string manipulation.
  • Trim or sanitize substrings after splitting if your data might include extra spaces or unwanted characters.
  • You should use preg_split() for complex patterns when you need to split by regular expressions, such as splitting on multiple delimiters or whitespace.
  • You must validate input strings before splitting to avoid unexpected results or errors with empty or malformed strings.
  • Always consider performance, like explode() is fastest for simple delimiters, while preg_split() can be slower due to regex processing.

Performance Comparison: explode vs str_split vs preg_split

Aspect explode() str_split() preg_split()
Best for Splitting by simple delimiters Splitting into fixed-length parts Splitting by complex patterns (regex)
Performance Very fast for simple splits (e.g., CSV fields, space-separated words) Very fast for fixed-length splits Slowest due to regex processing overhead
Delimiter/Pattern String delimiter Number of characters per chunk Regular expressions for advanced needs
Typical Use Case Splitting CSV fields, words separated by spaces Breaking a string into individual characters or fixed parts Splitting on multiple delimiters or patterns
Return Type Array of substrings Array of substrings Array of substrings
PHP Version Available since PHP 4 Available since PHP 5 Available since PHP 4

Common Pitfalls When Converting Strings to Arrays

  • Using the wrong function for the task, like using str_split() when you actually need to explode() for a delimiter-based split.
  • Forgetting to trim the input string before splitting can leave unwanted empty or whitespace-only elements in your array.
  • Not handling empty strings or missing delimiters can cause unexpected array results or single-element arrays.
  • Misunderstanding preg_split() patterns, leading to incorrect splits or unexpected empty array elements.
  • Overlooking multibyte character encoding, where str_split() can break characters in UTF-8 strings; use mb_str_split() instead to correctly convert multibyte string to array in PHP.
  • Failing to validate or sanitize input can lead to security issues or errors when processing untrusted strings.

Conclusion

In this article, we have covered various string conversion methods in PHP and functions. These are used to convert string to 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 string to array in PHP is a common but essential task in many web development scenarios, and crucial for effective PHP string manipulation.
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 in PHP?

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.

Q6. How to split a string into an array by a comma in PHP?

You can use explode(‘,’, $string); to split a string into an array by a comma in PHP.

Q7. What is the difference between explode() and str_split() in PHP?

explode() splits by a delimiter, while str_split() splits a string into fixed-length pieces.

Q8. Which PHP function is best for multibyte string conversion to an array?

The mb_str_split() PHP function is best for safely splitting multibyte (UTF-8) strings.

Q9. Can you convert multiple strings into arrays at once in PHP?

No, you cannot convert multiple strings into arrays at once in PHP directly. Loop over each string and then convert the strings individually.

Q10. When should I use preg_split() in PHP?

You can use preg_split() when you need to split strings using complex or multiple regex-based 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