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

phpstr_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<?php
  $str = 'abcde';
  $arr = str_split($str, 2);
  
  var_dump($arr);
?>

Code execution result:

php['ab', 'cd', 'e'];

Example

Let's split a string into chunks of 3 characters per array element:

php<?php
  $str = 'abcdefg';
  $arr = str_split($str, 3);
  
  var_dump($arr);
?>

Code execution result:

php['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<?php
  $num = 12345;
  echo array_sum(str_split($num, 1));
?>

Code execution result:

php15

See Also

  • the explode function,
    which splits a string into an array by a delimiter
  • the number_format function,
    which formats a number