PHP str_split: Convert String to Character Array
This article provides a quick guide on how to use the PHP
str_split() function to convert a string into an array. It
covers the function’s syntax, its default behavior of splitting by
individual characters, how to split strings into custom-sized chunks,
and how to safely handle multibyte UTF-8 characters.
The str_split() function is a built-in PHP function
designed to convert a string into an array of a specified length. By
default, it splits the string into single characters.
Syntax of str_split()
The function accepts two parameters:
str_split(string $string, int $length = 1): array$string: The input string you want to split.$length: The length of each array element. This is optional and defaults to1. If the length is less than1, aValueErroris thrown in PHP 8 and later.
Splitting a String into Single Characters
When you omit the second argument, str_split() defaults
to a length of 1. This converts the string into an array of individual
characters.
$string = "Hello";
$character_array = str_split($string);
print_r($character_array);Output:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
)
Splitting a String into Custom Chunk Sizes
You can split a string into larger chunks by specifying a custom length as the second argument. If the length of the string is not perfectly divisible by the specified chunk size, the final element in the array will contain the remaining characters.
$string = "PHPProgramming";
$chunk_array = str_split($string, 3);
print_r($chunk_array);Output:
Array
(
[0] => PHP
[1] => Pro
[2] => gra
[3] => mmi
[4] => ng
)
Handling Multibyte UTF-8 Characters
The str_split() function operates at the byte level.
This means if you use it on strings containing multibyte characters,
such as emojis or special accented characters, the characters will be
broken into corrupted byte sequences.
To convert strings with multibyte characters safely, use the
multibyte-safe mb_str_split() function instead:
$string = "Café";
// Incorrect: str_split will corrupt the "é"
$corrupt = str_split($string);
// Correct: mb_str_split safely preserves the "é"
$correct = mb_str_split($string);
print_r($correct);Output:
Array
(
[0] => C
[1] => a
[2] => f
[3] => é
)