What is str_split() function in PHP ?

The str_split() function splits the content of a string into an array.

This function is similar to the explode() function, but whereas the explode() function converts whole words that make up the string into separate arrays, the str_split() function converts every character in the string into an array item unless told otherwise.

explode() vs str_split()

Syntax

str_split($string, $length);

Parameters

  • $string: The first parameter will be a string whose content will be split into an array.
  • $length: The second parameter is an optional integer that will determine the length of the split chunks if provided.

Return value

  • If the $length parameter, which is optional, is passed, the returned array will have chunks with lengths equal to the provided $length. Otherwise, each item will be one character in $length.

  • The return value will be false if the length passed is less than 1.

  • If a $length value exceeds the string’s length, the whole string is returned as the first and only item of the array.

Support

This function is available for use in PHP version 5 and later.

Code

In the code snippet below, a string with the value "Welcome Back" is stored in $myString variable and passed to str_split().

In the first instance, we provide only a string parameter, while in the second instance, we also pass the $length parameter.

<?php
$myString = "Welcome Back";
print_r(str_split($myString));
print_r(str_split($myString, 4));
?>