The php str_split() function allows us to convert a string into an array of equal length substrings. By default, str_split() splits a string into an array of the string’s characters.

$variable = "I'm a variable";

print_r(str_split($variable));

//Output:
Array
(
    [0] => I
    [1] => '
    [2] => m
    [3] =>  
    [4] => a
    [5] =>  
    [6] => v
    [7] => a
    [8] => r
    [9] => i
    [10] => a
    [11] => b
    [12] => l
    [13] => e
)

You can also split a string into an array of equal length substrings of length n by passing a second argument to str_split().

$variable = "I'm a variable";

print_r(str_split($variable, 3));

//Output:
Array
(
    [0] => I'm
    [1] =>  a 
    [2] => var
    [3] => iab
    [4] => le
)

When working with string variables in our php programs, it is useful to be able to easily manipulate and change the value of the variables.

One such manipulation is being able to convert a string into an array of smaller strings.

The php str_split() function allows us the ability to convert a string into an array of substrings.

By default, str_split() splits a string into an array of the string’s characters.

Below is an example of using str_split() to convert a string into an array of the string’s characters.

$variable = "I'm a variable";

print_r(str_split($variable));

//Output:
Array
(
    [0] => I
    [1] => '
    [2] => m
    [3] =>  
    [4] => a
    [5] =>  
    [6] => v
    [7] => a
    [8] => r
    [9] => i
    [10] => a
    [11] => b
    [12] => l
    [13] => e
)

You can also split a string into an array of equal length substrings of length n by passing a second argument to str_split().

Below is a simple example of using str_split() and splitting a string into substrings of length 3.

$variable = "I'm a variable";

print_r(str_split($variable, 3));

//Output:
Array
(
    [0] => I'm
    [1] =>  a 
    [2] => var
    [3] => iab
    [4] => le
)

How to Loop Over Characters in String with str_split() Function in php

One example of how you can use the str_split() function is if you want to loop over all characters of a string variable.

We can first use str_split() to convert the string into an array of the string’s characters, and then loop over the array.

Below is an example of how to loop over the characters of a string in php.

$variable = "I'm a variable";

$chars = str_split($variable);

foreach($chars as $char) {
   echo $char . " ";
}

// Output:
I ' m   a   v a r i a b l e 

Hopefully this article has been useful for you to learn how to use the php str_split() function to convert a string into an array.

Categorized in:

PHP,

Last Update: March 13, 2024