Skip to content

Commit 14cef3d

Browse files
committed
Fix behavior of string->chunk() for empty string
This matches the PHP 8.2 str_split() behavior.
1 parent 12cf23c commit 14cef3d

File tree

3 files changed

+6
-3
lines changed

3 files changed

+6
-3
lines changed

doc/string_api.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,7 @@ length of the main string is not divisible by the chunk length, then the last ch
325325
>
326326
* This function corresponds to `str_split`.
327327
* It is perfectly valid to have a chunk length that is longer than the main string.
328+
* Chunking an empty string results in an empty array.
328329
* The name `chunk()` was chosen, because `split()` seems more appropriate for the `explode`
329330
equivalent. Furthermore the corresponding array functionality is also named `chunk()`.
330331

handlers/string.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,10 @@ public static function split($self, $separator, $limit = PHP_INT_MAX) {
125125

126126
public static function chunk($self, $chunkLength = 1) {
127127
$self->verifyPositive($chunkLength, 'Chunk length');
128+
if ($self === '') {
129+
// str_split() prior to PHP 8.2 is buggy and returns [''] instead.
130+
return [];
131+
}
128132
return str_split($self, $chunkLength);
129133
}
130134

tests/string.phpt

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -499,9 +499,7 @@ count(""): int(1)
499499
count("", 0): int(1)
500500
count("", 0, 0): int(1)
501501
repeat(3): string(0) ""
502-
chunk(3): array(1) {
503-
[0]=>
504-
string(0) ""
502+
chunk(3): array(0) {
505503
}
506504
replace("foo", "bar"): string(0) ""
507505
replace("foo", "bar", 1): string(0) ""

0 commit comments

Comments
 (0)