PHP is one of the most popular server-side scripting languages, offers numerous built-in functions to handle strings and arrays efficiently.
When working with data in PHP, you often need to convert strings to arrays. There are multiple ways to achieve this, depending on how the data is structured and what you need to accomplish.
In this brief tutorial, we will explore various PHP functions that can be used to convert strings to arrays, diving into their details, use cases, and examples.
1. The explode()
Function
The explode()
function is one of the most widely used methods for splitting a string into an array. It breaks a string into multiple parts based on a specified delimiter.
This is particularly useful when working with data formats like CSV (comma-separated values).
explode()
Syntax
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
- $separator: The delimiter that separates the string.
- $string: The input string to be split.
- $limit: (Optional) Maximum number of elements in the array. If not specified, the entire string is split.
Example
$string = "apple,banana,orange";
$array = explode(",", $string);
print_r($array);
Output
Array
(
[0] => apple
[1] => banana
[2] => orange
)
The explode() function splits the string at every occurrence of the delimiter and returns an array with the parts. If you want to limit the number of splits, you can specify the third parameter.
This function is perfect for scenarios where data is separated by a consistent delimiter, such as CSV data, or when parsing query strings from URLs.
2. The str_split()
Function
The str_split()
function splits a string into an array, with each character of the string becoming an array element.
This function is most useful when you need to manipulate or analyze individual characters of a string.
str_split()
Syntax
str_split(string $string, int $split_length = 1): array
- $string: The input string to be split.
- $split_length: (Optional) The number of characters per array element.
Example
$string = "hello";
$array = str_split($string);
print_r($array);
Output
Array
(
[0] => h
[1] => e
[2] => l
[3] => l
[4] => o
)
This function is ideal when you need to process individual characters of a string, for instance, in encryption algorithms, where character manipulation is common.
3. The preg_split()
Function
The preg_split()
function is a more powerful tool for splitting strings using regular expressions.
Unlike explode()
, which relies on a simple delimiter, preg_split() allows you to specify complex patterns, making it versatile for handling diverse data.
preg_split()
Syntax
preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array
- $pattern: The regular expression pattern used for splitting.
- $subject: The string to be split.
- $limit: (Optional) Maximum number of elements to split.
- $flags: (Optional) Additional flags that modify behavior.
Example
$string = "one1two2three3";
$array = preg_split("/\d/", $string);
print_r($array);
Output
Array
(
[0] => one
[1] => two
[2] => three
)
Use preg_split() when your delimiter is more complex than a single character, such as splitting by numbers or any non-alphabetic characters.
It provides the flexibility to split strings based on patterns, making it suitable for data sanitization and validation processes.
4. The mb_str_split()
Function
The mb_str_split()
function is specifically designed to handle multibyte character encodings like UTF-8.
This function ensures that characters that use more than one byte (such as non-Latin characters) are split correctly, unlike str_split()
, which can misinterpret such characters.
mb_str_split()
Syntax
mb_str_split(string $string, int $split_length = 1, string $encoding = null): array
- $string: The string to be split.
- $split_length: (Optional) Number of characters per array element.
- $encoding: (Optional) Character encoding to use.
Example
$string = "こんにちは";
$array = mb_str_split($string);
print_r($array);
Output
Array
(
[0] => こ
[1] => ん
[2] => に
[3] => ち
[4] => は
)
The mb_str_split() function is essential when working with multibyte character encodings, ensuring that strings with non-ASCII characters are split correctly.
It is a critical function for internationalized applications that need to handle various languages.
5. The json_decode()
Function
The json_decode() function is used to convert a JSON-formatted string into a PHP array.
This function is particularly helpful when working with API responses or other structured data formats where JSON is commonly used.
json_decode()
Syntax
json_decode(string $json, bool $assoc = false, int $depth = 512, int $flags = 0): mixed
- $json: The JSON-formatted string to decode.
- $assoc: (Optional) When true, JSON objects will be converted into associative arrays.
- $depth: (Optional) Specifies the recursion depth.
- $flags: (Optional) Flags that modify behavior.
Example
$json = '{"name":"John", "age":30, "city":"New York"}';
$array = json_decode($json, true);
print_r($array);
Output
Array
(
[name] => John
[age] => 30
[city] => New York
)
The json_decode() function is indispensable for decoding JSON data. This is especially relevant when dealing with API data, as JSON is the standard format for exchanging information across different systems.
6. The unserialize()
Function
The unserialize() function converts a serialized string back into a PHP array or object. Serialization is the process of converting data into a storable format, and unserialize() is its counterpart, used to restore data to its original form.
unserialize()
Syntax
unserialize(string $string, array $options = []): mixed
- $string: The serialized string.
- $options: (Optional) An array of options to control the behavior.
Example
$serialized = 'a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}';
$array = unserialize($serialized);
print_r($array);
Output
Array
(
[0] => apple
[1] => banana
[2] => orange
)
The unserialize() function is useful when you need to retrieve structured data from storage systems where data has been serialized for efficiency or transport.
This is common in session handling or caching mechanisms.
Conclusion PHP Functions to Convert String to Array
When working with strings in PHP, choosing the right method to convert a string into an array is essential for performance and functionality.
Whether dealing with simple delimiters, complex regular expressions, or structured data like JSON, PHP provides a robust set of tools to handle string-to-array conversions efficiently.