The str_split Function
The str_split function splits a string
into an array. Its first parameter is the
string, and the second is the number of characters per
array element. For example, if the second
parameter is set to 3, the function will split
the string into an array so that each element
contains 3 characters.
Syntax
str_split(string $string, int $length = 1): array
Example
Let's split a string into chunks of 2 characters
per array element (note that the last element is short
and contains not 2, but one character):
<?php
$str = 'abcde';
$arr = str_split($str, 2);
var_dump($arr);
?>
Code execution result:
['ab', 'cd', 'e'];
Example
Let's split a string into chunks of 3 characters
per array element:
<?php
$str = 'abcdefg';
$arr = str_split($str, 3);
var_dump($arr);
?>
Code execution result:
['abc', 'def', 'g'];
Example . Application
Let's find the sum of the digits of a number. To do this,
split the number into an array using str_split
and sum the elements of this array using
array_sum:
<?php
$num = 12345;
echo array_sum(str_split($num, 1));
?>
Code execution result:
15
See Also
-
the
explodefunction,
which splits a string into an array by a delimiter -
the
number_formatfunction,
which formats a number