PHP explode() function is a built-in string function in PHP. This function splits the string into parts and breaks it into an array. The explode() takes three parameters as arguments. The number one parameter is the “separator.” The separator parameter cannot be empty because it is the boundary string. It specifies the critical points, the points where the string will split. When this character is found in the string, it will show the end of one element of the array and the start of the second element of an array. The second parameter is “OriginalString.” It is the Original input string that will split into an array. The third parameter is “NoOfElements” or “limit.” This parameter is an optional argument; it specifies the number of elements in an array. The parameter can be any negative integer number, positive number, or zero. If we pass a positive number, it will show the number of elements that the array contains. If we pass a negative number, it will return the whole array except the last element because it will trim the last element. If we pass zero as a parameter, it will return the original string.
Table of Contents
In this example, we will perform an instance by applying three different conditions of “limit” the optional parameter and see what it is returning. The explode() function will return an array of strings.
<?php // original string $OriginalString = "Hello, How can we help you?"; // Without optional parameter NoOfElements print_r(explode(" ",$OriginalString)); echo "<br>"; // with positive NoOfElements print_r(explode(" ",$OriginalString,3)); echo "<br>"; // with negative NoOfElements print_r(explode(" ",$OriginalString,-1)); ?>
In conclusion, we discussed the PHP explode() function splitting a string into its parts and breaking it into an array. It was accepting three parameters from the two were required the “separator” and “OriginalString,” and one was optional, the “limit” or “NoOfElements.” One coding example is also given. It will make your concept clearer.