Core\Str::chunk
Core\Str::chunk(string $s, uint $size): array<string>Core\Str::chunk( string $s, uint $size, ): array<string>
Divides a string into pieces that each have the same number of characters.
Core\Str::chunk returns an array of strings in their original order. Every piece has the size you give, except the last one, which has what is left. Dividing "abcdefg" into pieces of 3 gives "abc", "def" and "g". An empty string gives an empty array.
The size counts characters the way a person sees them. An accented letter or an emoji is one character, so a piece never cuts one in half. The size must be at least 1. A size of 0 throws a RuntimeError.
The examples below divide a word into pairs of letters, show that accents and emoji stay whole, and format a long card number in groups of four digits.
Parameters
$sstringThe string to divide.$sizeuintHow many characters each piece has. It must be at least1.
Return value
Returns array<string>. The pieces in order. Only the last piece can be shorter than $size. The result is [] for the empty string.
Errors
RuntimeError$sizeis0.
Examples
Pairs of letters
<?nvs// Shows how to divide a string into pieces of the same size.
// Each piece has 2 characters. The last piece has only 1, because 7 is odd.// This prints `ab`, `cd`, `ef` and `g`, one on each line.foreach (Core\Str::chunk('abcdefg', 2) as string $piece) { echo $piece, "\n";}
// An empty string gives no pieces. This prints `0`.echo Core\Arr::count(Core\Str::chunk('', 2)), "\n";abcdefg0Accents and emoji stay whole
<?nvs// Shows that `Core\Str::chunk` counts characters, not bytes.
// "é" and each flag are stored as several bytes, but each is one character.// This prints `Ré|su|mé` and then `🇩🇪🇫🇷|🇯🇵`.echo Core\Str::join(Core\Str::chunk('Résumé', 2), '|'), "\n";echo Core\Str::join(Core\Str::chunk('🇩🇪🇫🇷🇯🇵', 2), '|'), "\n";
// A size of 0 is not allowed and throws an error.// This prints `Core\Str::chunk(): the chunk size must be at least 1`.try { Core\Str::chunk('abc', 0);} catch (RuntimeError $error) { echo $error->message, "\n";}Ré|su|mé🇩🇪🇫🇷|🇯🇵Core\Str::chunk(): the chunk size must be at least 1Group a card number
<?nvs// Shows how to print a long number in groups of four digits, as a payment page does.
string $cardNumber = '4111111111111111';
// This prints `4111 1111 1111 1111`.echo Core\Str::join(Core\Str::chunk($cardNumber, 4), ' '), "\n";
// An IBAN is written the same way. The last group is shorter.// This prints `DE89 3704 0044 0532 0130 00`.echo Core\Str::join(Core\Str::chunk('DE89370400440532013000', 4), ' '), "\n";4111 1111 1111 1111DE89 3704 0044 0532 0130 00