The explode() function converts a string into an array using a separator value.
PHP explode() Function has the following syntax.
array explode ( string separator, string input [, int limit] )
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 |
Turn a string value to an array
<?PHP// w w w . ja v a2 s. c om
$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.
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
$fruitString = "apple,pear,banana,strawberry,peach,java2s.com";
$fruitArray = explode( ",", $fruitString, 3 );
print_r($fruitArray);
?>
The code above generates the following result.
The following code shows how to break a string into an array and return an array except for the last -limit elements().
<?php
$str = 'one,two,three,four';
// negative limit
print_r(explode(',',$str,-1));
?>
The code above generates the following result.