PHP explode() Function
The PHP explode() function returns an array of strings, each element of which is a substring of the given string formed by splitting it using specified separator string.
Syntax
explode(separator, string, limit)
Parameters
separator |
Required. Specify the separator string used for splitting the string. |
string |
Required. Specify the input string. |
limit |
Optional. Specify the number of elements in the returned array.
|
Return Value
Returns an array of strings created by splitting the given string using separator string.
If separator is an empty string (""), explode() will return false. If separator contains a value that is not contained in the string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned. If separator values appear at the start or end of string, said values will be added as an empty array value either in the first or last position of the returned array respectively.
Example: explode() example
The example below shows the usage of explode() function.
<?php $str = "one|two|three|four|five"; //no limit echo "No limit: \n"; print_r(explode('|', $str)); //zero limit echo "\nZero limit: \n"; print_r(explode('|', $str, 0)); //negative limit echo "\nNegative limit: \n"; print_r(explode('|', $str, -2)); //positive limit echo "\nPositive limit: \n"; print_r(explode('|', $str, 3)); ?>
The output of the above code will be:
No limit: Array ( [0] => one [1] => two [2] => three [3] => four [4] => five ) Zero limit: Array ( [0] => one|two|three|four|five ) Negative limit: Array ( [0] => one [1] => two [2] => three ) Positive limit: Array ( [0] => one [1] => two [2] => three|four|five )
Example: using limit parameter
Consider one more example where the string starts and ends with the given sperator string.
<?php $str = "|one|two|three|"; //no limit echo "No limit: \n"; print_r(explode('|', $str)); //zero limit echo "\nZero limit: \n"; print_r(explode('|', $str, 0)); //negative limit echo "\nNegative limit: \n"; print_r(explode('|', $str, -2)); //positive limit echo "\nPositive limit: \n"; print_r(explode('|', $str, 3)); ?>
The output of the above code will be:
No limit: Array ( [0] => [1] => one [2] => two [3] => three [4] => ) Zero limit: Array ( [0] => |one|two|three| ) Negative limit: Array ( [0] => [1] => one [2] => two ) Positive limit: Array ( [0] => [1] => one [2] => two|three| )
❮ PHP String Reference