PHP str_split() function is “used to convert the string into an array.”
Syntax
str_split($string, $length)
Parameters
- $string: This is an input string.
- $length: It specifies the length of each array element. The default is 1.
Return value
If the length is larger than the length of the string, the entire string will be returned as the only element of the array.
If the string is empty, an empty array will be returned(PHP 8.2.0).
Visual Representation
Example 1: How to Use str_split() Function
<?php
$str = "AppDividend";
print_r(str_split($str));
Output
Array
(
[0] => A
[1] => p
[2] => p
[3] => D
[4] => i
[5] => v
[6] => i
[7] => d
[8] => e
[9] => n
[10] => d
)
Example 2: Using length parameter
<?php
$str = "AppDividend";
print_r(str_split($str,4));
Output
Array
(
[0] => AppD
[1] => ivid
[2] => end
)
In the above example, the string is split into chunks of four characters each, except for the last element which contains the remaining characters.
Example 3: Empty string
<?php
$str = "";
print_r(str_split($str));
Output
Array
(
[0] =>
)
That’s it for this tutorial.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.