Current Location: Home> Latest Articles> str_split behavior explanation when the second parameter is 0

str_split behavior explanation when the second parameter is 0

M66 2025-05-17

In PHP, the str_split() function is a very practical function used to split a string into an array. This function has two parameters:

  • The first parameter : the string to be split.

  • The second parameter : Specifies the length of each array element (i.e. the "block" size of the segmented).

When we pass 0 as the second parameter, the result may not be as we expected. Today we will explore in depth what happens when the second parameter of str_split() is 0.

Basic usage of str_split()

First, let's take a look at the basic usage of str_split() :

 $str = "abcdef";
$result = str_split($str, 2);
print_r($result);

The above code splits the string "abcdef" into an array of length 2 for each element, and the output will be:

 Array
(
    [0] => ab
    [1] => cd
    [2] => ef
)

When the second parameter is 0

Next, let's test what kind of behavior will str_split() behave when the second parameter is 0:

 $str = "abcdef";
$result = str_split($str, 0);
print_r($result);

Results Analysis

Run the above code and you will find that PHP will report an error:

 Warning: str_split(): The length of each chunk must be greater than 0 in /path/to/your/file.php on line X

This is because the str_split() function requires that the second parameter must be greater than 0. When 0 is passed, the function will issue a warning and will not perform a string split operation.

Why does this happen?

The second parameter of str_split() specifies the maximum length of each array element. If this value is 0, PHP internally considers this to be an invalid length, causing it to not handle the string properly. Therefore, it triggers a warning that the developer must have a second parameter greater than 0.

Summarize

Through the above analysis, we can conclude that when the str_split() function is called, the second parameter cannot be 0. If 0, PHP throws a warning and string splitting cannot be performed correctly. Therefore, it is important to always ensure that the valid block size (integrals greater than 0) is passed in.