PHP explode() Function
Definition
The explode() function converts a string into an array using a separator value.
Syntax
PHP explode() Function has the following syntax.
array explode ( string separator, string input [, int limit] )
Parameter
Parameter | Is Required | Description |
---|---|---|
separator | Required. | Separator to break the string |
string | Required. | String to split |
limit | Optional. | Number of array elements to return. |
Possible values for limit:
Return | Meaning |
---|---|
> 0 | Returns an array with a maximum of limit element(s) |
< 0 | Returns an array except for the last -limit elements() |
0 | Returns an array with one element |
Example
Turn a string value to an array
<?PHP/*from w w w .j av a 2 s . c o m*/
$oz = "A and B and C";
$oz_array = explode(" and ", $oz);
print_r($oz_array);
print_r("\n");
$fruitString = "apple,pear,banana,strawberry,peach";
$fruitArray = explode( ",", $fruitString );
print_r($fruitArray);
?>
The implode()
function is a reverse of this function.
It converts an array into a string by inserting a separator.
The code above generates the following result.
Example 2
You can limit the number of elements in the returned array with a third parameter, in which case the last array element contains the whole rest of the string:
<?PHP/*from ww w . jav a 2s . co m*/
$fruitString = "apple,pear,banana,strawberry,peach,java2s.com";
$fruitArray = explode( ",", $fruitString, 3 );
print_r($fruitArray);
?>
The code above generates the following result.