PHP explode() function
PHP explode() is a string function, which splits a string by a string. In simple words, we can say that it breaks a string into an array. The explode() function has a “separator” parameter, which cannot contain an empty string, because it holds the original string that is to be split. It is a binary-safe function.
The explode() function returns an array of strings created by splitting the original string.
Syntax:
Parameters
There are three parameters passed in the explode() function, in which two parameters are mandatory, and the last one is optional to pass. These parameters are as follows:
$separator:
This parameter specifies the character for the point at which the original string will split. In simple words, we can say that whenever this character is found in the string, the string will be divided into parts.
$originalString:
This parameter holds the string which is to be split into array.
$limit:
The $limit parameter specifies the number of array elements to be returned. It can contain any integer value (zero, positive, or negative).
Possible values for $limit:
Positive (Greater than 0) | If this parameter contains a positive value, this function returns an array of string, split into a size defined in the $limit parameter. |
Negative (Less than 0) | If the $limit parameter consists of the negative value, elements from the last will be trimmed, and the remaining will be returned. |
Zero | If zero (0) is passed in $limit parameter, it will return the whole string as a single array element. |
Note: Remember that, if the $limit parameter is not provided in explode() function, the returned array will contain all elements of string separated by the $separator string.
Return Value
This function returns an array of strings. This array of string is formed by splitting the original string.
Changes
After PHP version 5.1.0, negative value is allowed to provide in $limit parameter.
Examples
Example 1: Array with $limit parameter
Output:
In the above example, a space character is used as separator to split the string.
Array ( [0] => Hello, we are here to help you. ) Array ( [0] => Hello, [1] => we [2] => are [3] => here to help you. ) Array ( [0] => Hello, [1] => we [2] => are [3] => here )
The above output can be seen as to better understand:
Array ( [0] => Hello, we are here to help you. ) Array ( [0] => Hello, [1] => we [2] => are [3] => here to help you. ) Array ( [0] => Hello, [1] => we [2] => are [3] => here )
Example 1: Array without $limit parameter
Output:
In the above code, we do not pass the optional parameter, i.e., $limit. Therefore, the explode() function splits the string into array for different indexes.
Array ( [0] => Hello, [1] => welcome [2] => to [3] => TutorAspire . )
Example 3:
Output:
In the above code, we used the “e” character to split the string into an array. So, wherever the “e” is found, the string will be split.
Array ( [0] => H [1] => llo, w [2] => lcom [3] => to TutorAspire . )