为什么要在php中使用str_split()?

Given the following code :

$str = 'CLAX';
echo $str[2];  //prints 'A'

then why should I use str_split( $str ) to convert string to a array of characters ?

I understand str_split( $str , 2 ) will return array of strings; each string being 2 characters long.

http://php.net/manual/en/function.str-split.php

This function is to split a string into an array with given string split length

By default string split length is set 1

If you want to split a string into given in given length, then you can use str_split. But in your case you are splitting string with default length 1 that is by you are getting confused.

<?php

$str = "CLAX";
echo $str[2]; //here you are referring to 2 index of string

$arr2 = str_split($str);
Array
(
    [0] => C
    [1] => L
    [2] => A
    [3] => X
)
echo $str[2]; //here you are referring to 2 index of an array

str_split reference

<?php

$str = "Hello Friend";
$arr2 = str_split($str, 3);
Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)

Using str_split() comes in pretty handy when you want to leverage array functions to perform a task on the components in a string.

str_split() works like explode() except it doesn't care what the characters are, just their position in the string -- there are specific use cases for this.

Use Case #1: Group Array Elements by Letter Range

Rather than manually declaring an array with 3 letters per element, like this:

$chunks=['ABC','DEF','GHI','JKL','MNO','PQR','STU','VWX','YZ']

The same array can be produced with:

$chunks=str_split(implode(range('A','Z')),3);

This purely for demonstration. Of course, declaring it manually would be more efficient. The potential benefit for other cases is code flexibility and ease of code modification.


Use Case #2: Convert string to array at different character occurence

Use str_split() when using a foreach loop to process each character.

$string="abbbaaaaaabbbb";
$array=str_split($string);
$last="";
foreach($array as $v){
    if(!$last || strpos($last,$v)!==false){
        $last.=$v;
    }else{
        $result[]=$last;
        $last=$v;
    }
}
$result[]=$last;
var_export($result);

If you try to supply the foreach loop with $string php will choke on it. str_split() is the right tool for this job.


Use Case #3: Find element of an array those contains only specific character set in PHP

Use str_split() to in association with other array functions to check values in a way that string functions are not well suited for.

[I'll refrain from transferring the full code block across.]