+1 vote
in Programming Languages by (2.9k points)
How can I convert a string into an array of its characters in PHP? What PHP function should I use for it?

1 Answer

0 votes
by (28.9k points)

You can use the str_split() function to split a string into an array of its characters.

The syntax of the function is as follows:

str_split(string, n), where n specifies the length of each array element. The default value of n is 1.

Here is an example:

<?php
$str = "Hello World!!";
echo $str;
echo "\n";
// legnth of each array element = 1
print_r(str_split($str));
echo "\n";
// legnth of each array element = 2
print_r(str_split($str, 2));
?>

The above code will return the following output:

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

Array
(
    [0] => He
    [1] => ll
    [2] => o
    [3] => Wo
    [4] => rl
    [5] => d!
    [6] => !
)

...