String to Array in PHP: A List of Popular Functions for 2025

By Rohan Vats

Updated on Jun 16, 2025 | 13 min read | 8.76K+ views

Share:

Do you know? The PHP explode() function can split strings into arrays with millions of elements in just seconds, operating in linear time O(n) for single-byte delimiters—even when processing strings with over 10 million items. This demonstrates that explode() is highly efficient for handling large amounts of data in PHP.

Converting a string to array in PHP is a crucial operation for many programming tasks, especially when dealing with large datasets or parsing text. In real-world scenarios, such as processing CSV files or user input, this functionality is essential. 

For instance, converting a comma-separated string of items into an array allows easy manipulation of individual elements, like sorting a list of products or processing form data. Understanding how to do this efficiently is key to optimizing PHP applications.

In this article, we will look at some of the important functions of converting a string to array in PHP. We will look at each PHP function and see how it is written in the program.

Ready to take your development skills to the next level? Join upGrad's Online Software Development Courses to gain hands-on experience with real-world projects and expert guidance in PHP and other programming languages.

Converting String to Array in PHP: A List of Popular Functions

In many cases, an array is preferable to a string. For example, before storing the passwords in the database that the users enter in a web app, they can be converted into an array. Access to the data is made easier and more secure as a result. You can use arrays to achieve faster operations and better data organisation. PHP, a robust programming language, has several built-in methods for converting a string to an array.

In 2025, developers who can efficiently manipulate data, like converting strings to arrays in PHP, will be in high demand for building optimized web applications. If you’re looking to enhance your PHP and web development skills, here are some top-rated courses to help you get there:

There are basically four functions to convert String to Array in PHP:

Function

Description

str_split() Splits a string into array elements with the same length.
preg_split() Splits a string based on a regular expression, allowing for more complex delimiters.
explode() Splits a string by a specified delimiter and returns an array.
chunk_split() Splits a string into smaller parts without altering the original string, useful for formatting.

Let’s implement each of these functions and see how they convert String to Array in PHP.

1. str_split()

str_split function converts a string to an array in PHP. It splits into bytes, rather than characters with a multi-byte encoded string.

Syntax:

str_split ( $string , $length )

Parameters:

String – The given Input string.
Length – The maximum string length.

If the length is mentioned, the returned array breaks down into chunks of that length number, else, the chunk length of each will be by default, one character.

If the measure of length is more than the length of the string, the complete string returns as the first array element.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Example:

<?php

$str = "PHP String ”;

$arr1 = str_split($str);

$arr2 = str_split($str, 3);

print_r($arr1);

print_r($arr2);

?>
  • $arr1 = str_split($str); splits the string into individual characters.
  • $arr2 = str_split($str, 3); splits the string into chunks of 3 characters.

Output:

Array
(
   [0] => P
   [1] => H
   [2] => P
   [3] =>  
   [4] => S
   [5] => t
   [6] => r
   [7] => i
   [8] => n
   [9] => g
   [10] =>  
)

Array
(
   [0] => PHP
   [1] =>  St
   [2] => rin
   [3] => g 
)

You can begin your Python learning journey with upGrad’s free Python Programming with Python: Introduction for Beginners course. Learn core programming concepts such as control statements, data structures, like lists, tuples, and dictionaries, and object-oriented programming.

Also Read: Steps to Become a PHP Developer in 2025

Software Development Courses to upskill

Explore Software Development Courses for Career Progression

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

2. preg_split()

preg_split is a function that splits a string using a regular expression.

Syntax:

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

Parameters:
Pattern – The string pattern to be searched.
Subject – The input string.
Limit – Substrings up to the limit value specified. A -1 or 0 means “no limit”.
Flags – If this flag is set, the appendant string offset is returned.

Example:

<?php

$string = preg_split("/[\s,]/", "hypertext programming language ");

print_r($string);

?>
  • The string is split into individual words based on spaces (since \s matches any whitespace).
  • The regular expression /[\s,]/ also includes commas, but since there are no commas in the string, it only splits by spaces.
  • The last empty element in the array ([3] => ) is due to the trailing space at the end of the input string.

Output:

Array
(
[0] => hypertext
[1] => programming
[2] => language
)

You can get a better understanding of Python integration with upGrad’s Learn Python Libraries: NumPy, Matplotlib & Pandas. Learn how to manipulate data using NumPy, visualize insights with Matplotlib, and analyze datasets with Pandas.

Also Read: Best PHP Project Ideas & Topics for Beginners in 2025

3. chunk_split()

chunk_split is a function that splits a string into a smaller chunk and returns a chunked string as an output.

Syntax:

chunk_split( $string , $length , $separator = “\r\n” )

Parameters:
String - The string to be chunked.
Length - The length of the chunk.
Separator - The ending line sequence.

Example:

<?php

$str = "Hello World!";

echo chunk_split($str,1,".");

?>

Output:

H.e.l.l.o. .w.o.r.l.d.!.

4. explode()

 explode is a PHP function that splits a string by a string. It is faster than the preg_split() function and is binary-safe.

Syntax:

explode ( $separator ,$string ,$limit)

Parameters:

Separator - The string at the boundary.
String - The input string.
Limit - Specifies the length of the output string

Note: If the limit is set to be a positive value, the returned array will be the maximum limit of elements with the last element having the remnant string. If the limit is a negative value, all the string components excluding the last limit are returned. If the limit is zero, then it is assumed as 1.

The explode function splits the string parameter on boundaries limited by the separator and returns an array. If the separator is an empty string (“), it returns a false value.

If the separator consists of some value that is not the part of the string and a negative limit is used, an empty array is returned, else an array of the string will be returned.

Example:

<?php

$input1 = "hello";

$input2 = "hello,world";

$input3 = ',';

print_r( explode( ',', $input1 ) );

print_r( explode( ',', $input2 ) );

print_r( explode( ',', $input3 ) );

?>

Output:

array(1)
(
[0] => string(5) "hello"
)
array(2)
(
[0] => string(5) "hello"
[1] => string(5) "there"
)
array(2)
(
[0] => string(0) ""
[1] => string(0) ""
)

Are you a full-stack developer wanting to integrate AI into your workflow? upGrad’s AI-Driven Full-Stack Development bootcamp can help you. You’ll learn how to build AI-powered software using OpenAI, GitHub Copilot, Bolt AI & more.

Also Read: Interface in PHP | PHP OOPs Interfaces

Next, let’s look at an alternative methods to convert String to Array in PHP.

Subscribe to upGrad's Newsletter

Join thousands of learners who receive useful tips

Promise we won't spam!

Alternative Methods To Convert String To Array In PHP

Converting a string to array in PHP is essential for tasks like data parsing and processing user inputs. While common functions like explode(), str_split(), and preg_split() cover basic use cases, alternative methods such as substr(), array_map(), and custom logic offer greater flexibility for complex string manipulations. 

By exploring these alternatives, developers can choose the most efficient approach based on the specific needs of their project.

Here are some additional alternatives you can use to convert String to Array in PHP:

1. Manually Looping Through String

One alternative way to convert a string into an array in PHP is by manually looping through the string. This method gives you full control over how each character in the string is handled. It works by initializing a counter variable (like i) and iterating through the string until you've processed each character. You can then append each character to an array, ignoring spaces or handling them differently if needed.

This approach is useful when you want to perform additional operations during the string-to-array conversion, such as skipping certain characters or transforming data before adding it to the array.

Example Code:

<?php

$the_str = 'lorem ipsum';    
$the_ar = [];

for ($i = 0; $i < strlen($the_str); $i++) {
    if ($the_str[$i] != " ") { 
        $the_ar[] = $the_str[$i]; 
    }
}

echo "Final converted array: <br>";
print_r($the_ar); // l, o, r, e, m, i, p, s, u, m 

?>

Explanation:

  • A variable $the_str holds the string to be converted, and $the_ar is an empty array where the result will be stored.
  • The for loop runs through each character in the string using strlen($the_str) to get the length of the string.
  • Inside the loop, if the current character is not a space ($the_str[$i] != " "), it is added to the array $the_ar.
  • Finally, print_r() is used to display the contents of the array after conversion.

Output:

Final converted array: 
Array
(
   [0] => l
   [1] => o
   [2] => r
   [3] => e
   [4] => m
   [5] => i
   [6] => p
   [7] => s
   [8] => u
   [9] => m
)

Also Read: 12 Must-Have PHP Developer Skills for Success in 2025

2. Creating a Multidimensional Array from a String

To create a multidimensional array from a string, you can use the explode() function multiple times. This function splits a string based on a delimiter, allowing you to break down complex strings into smaller, more manageable pieces. 

For example, a string containing a person's full name and age can be split into a multidimensional array, where each piece of information (first name, last name, and age) is stored in a different part of the array.

Example Code:

<?php

$str = "Peter,Jacob,31";

// Split the string by commas
$arr1 = explode(",", $str); // $arr1 is now ["Peter", "Jacob", "31"]

// Split the first element (name) by space
$name = explode(" ", $arr1[0]); // $name is now ["Peter", "Jacob"]

// Extract age
$age = $arr1[2]; // $age is now "31"

// Create the multidimensional array
$newArr = [
    "first_name" => $name[0],
    "last_name" => $name[1],
    "age" => $age
];

print_r($newArr);

?>

Explanation:

  • The explode(",", $str) splits the string into three parts: "Peter", "Jacob", and "31".
  • Next, explode(" ", $arr1[0]) splits the first element of the array, "Peter", into two parts: "Peter" and "Jacob".
  • The age is simply stored in the variable $age as "31".
  • A new associative array, $newArr, is created, storing "first_name", "last_name", and "age" as keys, and the corresponding values as the split parts of the original string.

Output:
Array
(
   [first_name] => Peter
   [last_name] => Jacob
   [age] => 31
)

Using explode() multiple times allows you to easily transform a string into a multidimensional array, organizing related data into individual elements for easier manipulation and access. 

This approach is particularly useful when dealing with data in CSV-like formats or structured strings that require breaking down into distinct parts.

Also Read: Best PHP Developer Tools: Frameworks for Web Development

Next, let’s look at some of the best practices you can follow when converting String to Array in PHP.

Best Practices for Converting Strings to Arrays in PHP

Converting a string to an array is a fundamental task in PHP, commonly used for data parsing, form processing, and text manipulation. However, it's important to follow best practices to ensure that the conversion is done efficiently, avoiding errors and making the code easy to maintain.

Below are five best practices to follow when converting strings to arrays, along with examples showing why each practice is important:

1. Use explode() for Simple Delimited Strings

When dealing with strings that have clear delimiters (like commas, spaces, or semicolons), use explode() to split the string into an array. This function is simple, efficient, and widely used for handling structured data like CSVs or user input.

Example:

$string = "apple,banana,orange";
$array = explode(",", $string);
print_r($array); // ["apple", "banana", "orange"]

Why It Works? explode() is specifically designed to handle such use cases, making it the fastest and most efficient method for splitting strings by delimiters.

2. Handle Multiple Delimiters with preg_split()

When a string contains multiple delimiters or complex patterns (like spaces, commas, or special characters), preg_split() offers flexibility with regular expressions to handle diverse cases.

Example:

$string = "apple, orange; banana|grape";
$array = preg_split("/[\s,;|]+/", $string);
print_r($array); // ["apple", "orange", "banana", "grape"]

Why It Works? preg_split() allows you to use regular expressions to specify complex delimiters, making it ideal for cases where multiple delimiters or patterns need to be handled in a single operation.

3. Avoid str_split() for Complex Splits

While str_split() can be useful for splitting strings into fixed-length chunks, it's best suited for cases where each chunk is of equal length. For more complex splits (e.g., words or phrases), use other methods like explode() or preg_split().

Example:

$string = "hello world";
$array = str_split($string, 5);
print_r($array); // ["hello", " worl", "d"]

Why It Works? While str_split() is useful for breaking strings into fixed-length parts, it isn't ideal for splitting strings based on meaningful content like words or sentences. It can produce uneven results unless the string length is perfectly divisible by the chunk size.

4. Trim Unwanted Whitespace Before Converting

Always trim leading and trailing whitespace before splitting a string to prevent empty elements in your array. This is especially useful when dealing with user input or data that may contain extra spaces.

Example:

$string = "  apple, banana , orange  ";
$array = explode(",", trim($string));
print_r($array); // ["apple", "banana", "orange"]

Why It Works? By trimming the string first, you eliminate unwanted spaces that might cause empty array elements or incorrect data splitting, ensuring a cleaner and more predictable result.

5. Validate Input Data Before Conversion

Always validate and sanitize input data before performing any conversion. This ensures that the string is in the expected format and prevents errors or malicious input from breaking your code.

Example:

$string = "apple,orange,123";
if (preg_match("/^[a-zA-Z, ]*$/", $string)) {
   $array = explode(",", $string);
   print_r($array); // ["apple", "orange", "123"]
} else {
   echo "Invalid input.";
}

Why It Works? Validating input ensures that you’re working with the correct data type and format before converting it, reducing the risk of errors, such as unexpected characters, and improving the security and reliability of your application.

Also Read: PHP Developer Resume Examples & Writing Guide 2025

Next, let’s look at how upGrad can help you learn PHP programming.

How Can upGrad Help You Learn PHP Programming?

When converting strings into arrays in PHP, it’s crucial to choose the right method based on the data structure, ensure input validation, and handle delimiters effectively. These skills are essential for processing user input, parsing data, and building efficient web applications. 

Mastering these techniques with upGrad will enhance your problem-solving abilities and make you more attractive to employers, as PHP is widely used in web development. 

Along with the programs covered in the blog above, here are some additional courses to complement your learning journey:

If you're unsure where to begin or which area to focus on, upGrad’s expert career counselors can guide you based on your goals. You can also visit a nearby upGrad offline center to explore course options, get hands-on experience, and speak directly with mentors!

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

References:
https://app.studyraid.com/en/read/11843/376432/optimizing-performance-with-explode
https://stackoverflow.com/questions/5861826/performance-comparison-call-explode-in-foreach-signature-versus-passing-exp

Frequently Asked Questions (FAQs)

1. How do I convert a string to array while preserving empty elements when using explode() with consecutive delimiters?

By default, explode() preserves empty elements when consecutive delimiters are found, but you need to be careful with the limit parameter. Use explode(',', 'a,,b,c') which returns ['a', '', 'b', 'c'] with empty string preserved. If you want to remove empty elements, combine with array_filter(): array_filter(explode(',', $string), 'strlen'). To handle multiple consecutive delimiters differently, use preg_split() with PREG_SPLIT_NO_EMPTY flag. Always specify the limit parameter as -1 in explode() to ensure all occurrences are split without limitation.

2. What's the most efficient way to convert a large CSV string to a multidimensional array while handling quoted fields with commas?

Use str_getcsv() for single-line CSV or fgetcsv() with a string stream for multi-line CSV data, as these functions properly handle quoted fields containing delimiters. For large strings, create a temporary stream: $stream = fopen('data://text/plain,' . $csvString, 'r') and use fgetcsv($stream). This approach correctly parses "field1","field,with,commas","field3" without breaking on internal commas. For better memory efficiency with very large CSV strings, process line by line using strtok() or fgets() on the stream. Always specify the delimiter, enclosure, and escape characters explicitly in str_getcsv() for consistent parsing.

3. How can I convert a JSON string to array while handling nested objects and maintaining proper data types?

Use json_decode($string, true) with the associative parameter set to true to convert all objects to associative arrays. Handle potential errors with json_last_error() and json_last_error_msg() to catch malformed JSON. For nested structures, the second parameter affects all levels, so json_decode($json, true) converts everything to arrays. To preserve specific data types like integers and booleans, avoid using array_map('strval', $array) after conversion. Use JSON_BIGINT_AS_STRING flag if dealing with large integers that exceed PHP's integer limits: json_decode($string, true, 512, JSON_BIGINT_AS_STRING).

4. Why does explode() sometimes return unexpected results with multibyte characters, and how do I handle UTF-8 strings properly?

explode() works byte-wise, not character-wise, so it handles UTF-8 correctly as long as your delimiter is also UTF-8 encoded properly. Issues arise when mixing character encodings or using single-byte functions on multibyte strings. Use mb_split() instead of explode() when working with multibyte regular expression delimiters: mb_split('[,、]', $string) for Asian punctuation. Always ensure your PHP script, database, and input data use consistent UTF-8 encoding. Set mb_internal_encoding('UTF-8') at the beginning of your script and use mb_string functions when dealing with character-based operations rather than byte-based ones.

5. How do I convert a string containing serialized PHP data back to an array safely without security risks?

Use unserialize() with the allowed_classes option to restrict which classes can be instantiated: unserialize($string, ['allowed_classes' => false]) for arrays only. Always validate the input source and consider using JSON instead of serialize() for data storage to avoid object injection vulnerabilities. For unknown or untrusted data, use a whitelist approach: unserialize($data, ['allowed_classes' => ['stdClass', 'MyClass']]). Pre-validate serialized strings with a regex pattern to ensure they contain only expected data types before unserializing. Consider using igbinary or msgpack extensions for better performance and security when dealing with serialized data regularly.

6. What's the best approach to split a string into an array based on multiple different delimiters while preserving the delimiter information?

Use preg_split() with capturing groups to preserve delimiters: preg_split('/([,;|])/', $string, -1, PREG_SPLIT_DELIM_CAPTURE) returns both parts and delimiters. This creates an array where odd indices contain the split parts and even indices contain the matched delimiters. For complex delimiter patterns, combine multiple delimiters in the regex: preg_split('/([,;|:])/', $string, -1, PREG_SPLIT_DELIM_CAPTURE). To handle escaped delimiters, use negative lookbehind: preg_split('/(?<!\\)([,;])/', $string, -1, PREG_SPLIT_DELIM_CAPTURE). Process the resulting array by iterating through it and handling parts and delimiters separately based on array index parity.

7. How do I convert a string to an array of individual characters while properly handling emoji and Unicode combining characters?

Use mb_str_split($string, 1, 'UTF-8') which properly handles multibyte characters including emoji and combining characters as single units. This function is available in PHP 7.4+; for older versions, use preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY). The 'u' modifier ensures Unicode handling. For grapheme clusters (like emoji with skin tone modifiers), use grapheme_str_split() from the intl extension if available. Always specify UTF-8 encoding explicitly: mb_str_split($string, 1, 'UTF-8') to avoid encoding issues. Test with complex Unicode strings containing emoji, accents, and combining characters to ensure proper character boundary detection.

8. How can I convert a query string to an associative array while handling duplicate parameter names and nested arrays?

Use parse_str($queryString, $output) which automatically handles duplicate names by creating arrays and supports nested array syntax like param[key]=value. For duplicate parameters, PHP automatically converts them to arrays: "a=1&a=2" becomes ['a' => ['1', '2']]. To handle complex nested structures, parse_str() supports bracket notation: "user[name]=John&user[age]=30" creates nested arrays. Always use the second parameter to avoid polluting the global scope with variables. For custom handling of duplicates or different parsing logic, manually explode by '&' and '=' then process each key-value pair with proper URL decoding using urldecode().

9. What's the most memory-efficient way to convert a very large string to an array when the string exceeds available memory?

Process the string in chunks using file streams or generators to avoid loading everything into memory at once. Create a generator function that yields array elements: function stringToArrayGenerator($string, $delimiter) { $pos = 0; while(($next = strpos($string, $delimiter, $pos)) !== false) { yield substr($string, $pos, $next - $pos); $pos = $next + 1; } }. For file-based strings, use fgets() or fread() with small buffer sizes to process incrementally. Use SplFileObject for line-by-line processing of large files: $file = new SplFileObject('data.txt'); foreach($file as $line) { /* process */ }. This approach prevents memory exhaustion while maintaining functionality for massive datasets.

10. How do I handle string to array conversion when the string contains escaped characters or special formatting?

Use stripslashes() before conversion if dealing with escaped quotes, or preg_replace() for custom escape sequences: preg_replace('/\\(.)/', '$1', $string). For CSV-like data with escaped delimiters, use str_getcsv() which handles escaping automatically. When dealing with JSON-like strings that aren't valid JSON, manually parse escape sequences: str_replace(['\n', '\t', '\r'], ["\n", "\t", "\r"], $string). For complex escape patterns, use preg_replace_callback() to handle each escape sequence individually: preg_replace_callback('/\\(.)/', function($m) { return $m[1] === 'n' ? "\n" : $m[1]; }, $string). Always sanitize and validate input strings before processing to prevent injection attacks or unexpected behavior.

11. Why does array conversion fail when my string contains null bytes or control characters, and how do I handle it?

Null bytes (\0) and control characters can break string processing functions because they're treated as string terminators in some contexts. Use strlen() vs mb_strlen() to detect null bytes: if(strlen($string) !== mb_strlen($string)) indicates binary data presence. Clean the string before conversion: $clean = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $string) removes most control characters. For null bytes specifically, use str_replace("\0", "", $string) or trim($string, "\0"). When dealing with binary data that must preserve these characters, use binary-safe functions and consider base64 encoding before string operations: base64_encode($binaryString) for safe processing.

12. How do I convert a string to array while maintaining the original string's whitespace structure and formatting?

Use preg_split() with PREG_SPLIT_NO_EMPTY flag disabled to preserve empty elements caused by whitespace: preg_split('/\s+/', $string) removes all whitespace, while preg_split('/ /', $string) preserves other whitespace types. To maintain exact whitespace, split on specific characters only: explode(' ', $string) preserves tabs and newlines within elements. For complex whitespace preservation, use preg_split('/(\s+)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE) to capture whitespace as separate elements. When processing formatted text like code or poetry, consider using explode("\n", $string) to split by lines first, then process each line individually. Use trim() selectively on individual elements rather than the entire string to maintain internal formatting while removing boundary whitespace.

Rohan Vats

408 articles published

Rohan Vats is a Senior Engineering Manager with over a decade of experience in building scalable frontend architectures and leading high-performing engineering teams. Holding a B.Tech in Computer Scie...

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

upGrad

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

IIIT Bangalore logo
new course

Executive PG Certification

9.5 Months