Differences between str_split() and explode() in PHP

Welcome back again. We know both of the function str_split() and explode() in PHP are used to split strings. But here are some differences between them. I will describe shortly about this.



explode() is used to split any string by another string. This means if any string is same that will be missed from the main string and main string will be divided in that point. Here this divider string is as a junction as example.

<?php 

$str = "This is a text which will be used to do something.";

print_r(explode("t",$str));

?>

On the other hand the str_split() is used to split the whole string without missing anything.

<?php 

$str = "This is a text which will be used to do something.";

print_r(str_split($str));

?>

explode() function should contain two parameters.

<?php 

$str = "This is a text which will be used to do something.";

print_r(explode("t",$str));

?>

str_split() can work with only a single parameters.

<?php 

$str = "This is a text which will be used to do something.";

print_r(str_split($str));

?>


explode() splits the string in the matching part of the first parameter and delete the matched part,

<?php 

$str = "This is a text which will be used to do something.";

print_r(explode("text",$str));

?>


But str_split() do not delete anything, just separates the characters.

<?php 

$str = "This is a text which will be used to do something.";

print_r(str_split($str,5));

?>


str_split() splits the string according to given length. If the length is not given it splits one by one.

<?php 

$str = "This is a text which will be used to do something.";

print_r(str_split($str));
print_r(str_split($str,5));
print_r(str_split($str,10));

?>


The second parameter of str_split() must be a long or integer number.

<?php 

$str = "This is a text which will be used to do something.";

print_r(str_split($str,5));
print_r(str_split($str,10));

?>


str_split() is used to split but explode() is used to divide into two based on the matching parts. Again str_split() operates based on the second parameter while  explode() operates based on first parameter.

Hope you will find your answers.

Happy programming.

Related Posts
Previous
« Prev Post