In this write-up, you will be learning the use of str_shuffle() and str_split() functions in php. Both of these are string functions. While str_shuffle() is used to rearrange a string by mixing it up randomly, str_split() is used to split or convert a string into an array of elements.
It may be noted that the str_split() function does the same work as explode() function do. However, it doesn’t uses another string parameter to break or convert the given string into arrays of elements.
The description of str_shuffle() and str_split() functions is shown below.
STR_SHUFFLE() FUNCTION
As described earlier, this function is used to shuffle(rearrange) a string by jumbling it up randomly. The syntax is shown below.
Syntax : str_shuffle($str);
Here, the parameter $str represents the given string to be shuffled or rearranged.
Result/ Return Value : It will return the shuffled string on the successful execution of the function.
Errors : It is a simple function to implement thus having less probability of error occurrence.
Example : We have shown below an example of str_shuffle() function.
Output : You will get the following output of the above php script. Here, we have used $res variable to store the value of the string. After running the above php script, you can see that the string has been shuffled to a new value as shown below. This value will get changed every time you refresh the page. You can try it in your own.
STR_SPLIT() FUNCTION
This function is used to break a string into an array of elements without the use of another string. Hence, making it more easy and simple as compared to the explode function.
Syntax : str_split($str, $division);
Two parameters are used in this function.
- $str- It represents the string to be converted into an array of elements.
- $divisions- it represents the maximum length of the divisions to be made. It is an optional parameter.
Result/ Return Value : It will return an array of strings. If the division parameter is set, the resulting array will correspond to the value of the division. False will be returned if the value of the division is less than 1.
Errors : No such influencing errors.
Example : An example of str_split() function is shown below.
Output : The following output will be generated after running the above php script. Here, we have taken ‘W3Training School’ as a string and stored it in the $str variable. First, we have excluded the $division parameter which results in the proper conversion of the string into an array without any divisions. In the next step, we have taken the $division parameter into consideration by assigning value 5 to it. As a result of which the string is divided into four groups of arrays as shown in the image below.
We have tried to give you the best possible description on the use of str_shuffle() and str_split() functions in php. Hope you liked this article. For further updates and related information, stay connected to our php blogs.