PHP explode() function is a built-in Function in PHP. This function splits the string into parts and breaks it into an array.
In this blog post you will learn how to use PHP function EXPLODE(), which is used for splitting a string into an array. This function can be used in many ways and with various parameters to achieve different results.
It allows programmers the ability to break apart strings or arrays of data by using wildcard characters such as asterisk (*) or question mark (?).
Table of Contents
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 delimeter 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. In this way it will play with array elements.
The second parameter is “OriginalString.” It is the Original input string that will split into an array. The third parameter is “NoOfElements” or “limit parameter.” 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.
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 inbuilt function explode() splitting a string variable 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 parameter” or “NoOfElements.” One coding example is also given. It will make your concept clearer.