How To Convert PHP String to Array

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 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:

In the above example, I have taken a string separated by a space. We use the explode function to convert string to an array by passing a delimiter a space (‘ ‘) as the first argument. The second argument is the source string.

Output:

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:

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:

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:

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.