How to Convert a String to an Array in PHP

As a PHP programmer, you may encounter situations where you need to convert a string into an array.

This could be because you need to process each individual character, or because you need to access the contents of the string in a more organized manner.

In this tutorial, we will look at different ways to convert a string to an array in PHP.


Using str_split() Function

The simplest way to convert a string to an array in PHP is by using the str_split() function.

This function takes two arguments, the first one being the string that you want to convert, and the second being the maximum length of each chunk.

For example:

$string = "Hello, World!";
$array = str_split($string);
print_r($array);

Output:

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] => ,
    [6] =>  
    [7] => W
    [8] => o
    [9] => r
    [10] => l
    [11] => d
    [12] => !
)

As you can see, the string has been split into individual characters and stored in the array.

Using preg_split() Function

If you want to split a string based on a specific pattern, you can use the preg_split() function.

This function takes two arguments, the first being the pattern that you want to split the string on, and the second being the string that you want to split.

For example:

$string = "Hello, World!";
$array = preg_split('/[\s,]+/', $string);
print_r($array);

Output:

Array
(
    [0] => Hello
    [1] => World!
)

As you can see, the string has been split on the basis of spaces and commas and stored in the array.

Using explode() Function

The explode() function is similar to preg_split() but is easier to use when you want to split a string on a specific character or set of characters.

This function takes two arguments, the first being the delimiter that you want to split the string on, and the second being the string that you want to split.

For example:

$string = "Hello, World!";
$array = explode(',', $string);
print_r($array);

Output:

Array
(
    [0] => Hello
    [1] =>  World!
)

As you can see, the string has been split on the basis of commas and stored in the array.


Conclusion

Converting a string to an array in PHP is a simple task that can be done in a variety of ways.

Whether you need to split a string based on a specific pattern or on a specific character, there is a function available in PHP that can help you achieve this.

In this tutorial, we looked at three such functions – str_split(), preg_split(), and explode().

I hope this tutorial has helped you understand how to convert a string to an array in PHP.