str_split

Splits a string into an array of chunks of a given byte length, one byte per element by default.

Signature
str_split(string $string, int $length = 1): array
  • Added in PHP 5.0

Parameters

ParameterTypeDescription
$stringstringThe input string.
$lengthoptionalint= 1Maximum length of each chunk, in bytes.

Return value

arrayAn array of string chunks. If length is larger than the string, the array contains one element holding the whole string.

Errors

Throws a ValueError if length is less than 1.

Changelog

  • PHP 8.2.0An empty string now returns an empty array. Previously it returned an array containing one empty string.
  • PHP 8.0.0A length below 1 now throws a ValueError. Previously it raised E_WARNING and returned false.

str_split cuts a string into fixed-size pieces and hands you back an array. With the default length of 1 you get one array element per byte, which is the usual way to turn a string into something you can foreach, array_map or sort.

When to reach for it

Use it for fixed-width data: splitting a hex string into byte pairs, grouping a card number into blocks of four, walking a string character by character, or feeding characters into array_count_values() for a frequency tally. The final chunk may be shorter than length, which is normal and not an error.

What trips people up

The big one is encoding. str_split counts bytes, not characters. On a UTF-8 string with any accented letter, emoji or non-Latin script, it will slice through the middle of a multi-byte sequence and produce array elements that are not valid text. Use mb_str_split() for code points, or grapheme_str_split() for user-perceived characters like flag emoji.

Two edge cases also changed recently. Since PHP 8.2 an empty input returns [] rather than [''], so code counting on one element breaks. And since PHP 8.0 a length of 0 or lower throws a ValueError instead of quietly returning false.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Split a hex string into two-character byte pairs before converting it
  • Format a long account or card number into groups of four for display
  • Count character frequencies by combining it with array_count_values

Frequently asked questions

What is the difference between str_split and mb_str_split?

str_split splits by bytes, so it breaks multi-byte UTF-8 characters apart; mb_str_split splits by characters and keeps them intact. Use mb_str_split for any text that is not pure ASCII.

Does str_split return false on an empty string?

No. Since PHP 8.2 an empty string returns an empty array; before 8.2 it returned an array containing a single empty string. It never returns false for an empty input.

How do I split a string into an array of single characters?

Call str_split($string) with no second argument for ASCII, or mb_str_split($string) if the text may contain accented or non-Latin characters.

More examples

Formatting a number into groups

The card number prints as "4111 1111 1111 1111", and the hex string becomes ['de','ad','be','ef'] ready for hexdec() or chr(). Note the last chunk would simply be shorter if the length did not divide evenly.

Example · php
<?php
$card = '4111111111111111';
echo implode(' ', str_split($card, 4)), "\n";

$hex = 'deadbeef';
print_r(str_split($hex, 2));

The multi-byte trap

strlen reports 5 because é occupies two bytes. str_split produces five elements, the last two of which are invalid on their own, while mb_str_split correctly returns four elements ending in é.

Example · php
<?php
$s = 'café';
var_dump(strlen($s));       // int(5) - bytes, not letters
print_r(str_split($s));     // é is torn into two broken bytes
print_r(mb_str_split($s));  // one clean element per character

Counting characters and handling a bad length

The frequency table shows m=1, i=4, s=4, p=2. The try block demonstrates the PHP 8.0 behaviour change: a length below 1 throws a ValueError rather than returning false.

Example · php
<?php
print_r(array_count_values(str_split('mississippi')));

try {
    str_split('abc', 0);
} catch (ValueError $e) {
    echo 'ValueError: ', $e->getMessage(), "\n";
}

Discussion

  • Be the first to comment on this lesson.