In this post, we’ll learn how to convert a String to an Array in PHP. The PHP language includes functions for converting strings to arrays.
There is a number of ways to convert a String to an Array in PHP. We’ll discuss explode(), preg_split() and str_split() methods with example.
Convert Strings to Arrays in PHP
PHP provides functions that convert strings to arrays. The explode() function separates a string when the specified delimeter is found. The preg_split() function splits a string into an array using a regular expression. The str_split() function divides a string into equal-length array components.
PHP string to array explode()
The explode() function is used to break a string into an array, Whereas implode function returns a string from the elements of an array.
Syntax:
string join( $separator, $array)
The sample example:
$str = "Hi, I am phpflow blog.";
$arr = explode(" ", $str);
echo "";
print_r($arr);In the above example, I have taken a string separated by a space. We use the explode function to convert a string to an array by passing a delimiter a space (‘ ‘) as the first argument. The second argument is the source string.
Output:
Array
(
[0] => Hi,
[1] => I
[2] => am
[3] => phpflow
[4] => blog.
)PHP string to array preg_split()
The PHP preg_split() function, like the explode function, turns strings to arrays. The primary difference is that preg_split specifies the delimiter using a regular expression.
Syntax:
preg_split(pattern, string, limit, flags)
Where parameters are:
– pattern(Required): A regular expression determining what to use as a separator.
– string(Required): The source string that is being split.
– limit(Optional): Defaults to -1.It limits the number of elements that the returned array can have.
– flags(Optional): This provide options to change the returned array using Flag(PREG_SPLIT_NO_EMPTY, PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_OFFSET_CAPTURE).
The sample example:
$str = "Hi, I am phpflow blog."; $pattern = "/\s+/"; $arr = preg_split($pattern, $str); echo "</pre>"; print_r($arr);
In the above example, I have taken a string separated by a space. I have used “/\s+/” regular expression to split string by space.
Output:
Array
(
[0] => Hi,
[1] => I
[2] => am
[3] => phpflow
[4] => blog.
)PHP string to array using str_split()
The PHP str_split() function converts its string argument to an array with elements of equal length. You can pass a length as the second argument :
Syntax:
str_split(string $string, int $length = 1): array
Where parameters are:
– string(Required): The input string.
– length(Optional): Maximum length of the chunk.
The sample example:
$str = "Hi, I am phpflow blog."; $arr = str_split($str, 3); echo "</pre>"; print_r($arr);
Output:
Array
(
[0] => Hi,
[1] => I
[2] => am
[3] => php
[4] => flo
[5] => w b
[6] => log
[7] => .
)
















