Computer >> Computer tutorials >  >> Programming >> PHP

Explain str_split() function in PHP


PHP offers different kinds of inbuilt functions having particular functionalities. The str_split() is a predefined function in PHP and is utilized to convert the given string into an array.

This function works in such a way that it parts the given string into smaller strings of length, the length is determined by the user input and then stores the components in an array and return the array.

Now let' discuss the parameters.

Parameters

The function acknowledges two parameters and is explained underneath

string(mandatory)

This means the string that needs to convert into an array.

splitting length (optional)

This means to the length of each array segment, we wish to part our string into. By default, the function acknowledges the value as 1.

Example

<?php
   $string = "TutorialsPoint";
   print_r(str_split($string));
   $string = "WelcomeTo Tutorials Point";
   print_r(str_split($string, 4))
?>

Output

Array
(
[0] => T
[1] => u
[2] => t
[3] => o
[4] => r
[5] => i
[6] => a
[7] => l
[8] => s
[9] => P
[10] => o
[11] => i
[12] => n
[13] => t
)
Array
(
[0] => Welc
[1] => omeT
[2] => o Tu
[3] => tori
[4] => als
[5] => Poin
[6] => t
)

Explanation

In the above example, in the first expression, we have not passed any parameter as the length of an array segment, so by default, it converts the string into an array with a single component.

In the second expression we have passed the segment length as "4", so it converts the string into an array having one segment of length 4.