PHP Reference · String Functions
PHP str_split() function
Reference for PHP str_split(): split a string into an array of fixed-size byte chunks, what happens with empty strings in PHP 8.2, and the UTF-8 pitfall.
str_split() cuts a string into pieces of a fixed length and returns them as an array. With the default length of 1 you get one element per byte, which makes it a quick way to loop over the characters of an ASCII string.
It works on bytes. For text that may contain accented letters, emoji or non-Latin scripts, use mb_str_split() instead, otherwise a multibyte character can be cut in half.
<?php print_r(str_split("abcdef", 4)); // ["abcd", "ef"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
str_split(string $string, int $length = 1): array
| Name | Description |
|---|---|
$string |
The string to split. |
$length |
The size of each chunk in bytes. Must be at least 1. The last chunk may be shorter. |
Return value: an array of strings. For an empty input the result is an empty array since PHP 8.2; before that it was [""].
Errors: throws a ValueError if $length is less than 1.
Usage notes
- Byte-based.
"é"takes two bytes in UTF-8 and is split into two broken pieces. Usemb_str_split()for characters. - Not a delimiter split. To split on a separator, use
explode()orpreg_split(). - Empty input returned
[""]before PHP 8.2; code that relied on one element should be updated. - Characters by index:
$s[0]reads a single byte without building an array, which is cheaper in loops. - Chunking arrays is a different function:
array_chunk().chunk_split()returns a string, not an array (chunk_split()). - Large strings produce large arrays; for very long input iterate by offset instead.