PHP Spit String
In order to split a string in PHP, you can use a built-in function called explode()
. This function requires at least two params: First param is a separator and second param is a string that you want to split. Third param is optional and it's the integer that specifies number of array elements to return.
$text = 'I love pizza';
$out = explode(' ', $text);
print_r($out);
/* ๐๏ธ Array
(
[0] => I
[1] => love
[2] => pizza
)
*/
As you can see, the result of the explode()
function in the example above is an array with three items. We specified the separator to be whitespace, thus the text was split by it.
Warning: Separator is required param, if you omit it, the function will throw ValueError if using PHP version 8.0.0 or above, or it will return false in case of previous versions.
Another thing to keep in mind is that if you pass an empty string as a second parameter, you'll get an array with one item (empty string).
$out = explode(':', '');
print_r($out);
/* ๐๏ธ Array
(
[0] =>
)
*/
The resulting array contains one item even if the separator was not encountered and even when the string is empty altogether. This is important when working with unknown values and if you then check the length of resulting array for any conditions.
$text = "I love ๐ and ice cream";
$out = explode('๐', $text);
print_r($out);
/* ๐๏ธ Array
(
[0] => I love
[1] => and ice cream
)
*/
The example above is to demonstrate that you can use any unicode characters as separators in the explode() function.
$text = 'I love pizza and ice cream';
$out = explode(' ', $text, 2);
print_r($out);
/* ๐๏ธ Array
(
[0] => I
[1] => love pizza and ice cream
)
*/
We passed an integer as third param to limit the number of array elements returned from the function. In other words, we only separated the text in the first occurence of separator, no matter how many whitespaces are in the rest of the string.
$text = 'I love pizza and ice cream';
$out = explode(' ', $text, -1);
print_r($out);
/* ๐๏ธ Array
(
[0] => I
[1] => love
[2] => pizza
[3] => and
[4] => ice
)
*/
If we pass negative integer, the split occurs on the whole string but the result will be an array with number of items minus the specified value. In our example, there would be 6 items but since we specified integer as -1, the result only contains 5 items in the array. The items are removed from the end of the array.