PHP explode() Function
In this chapter you will learn:
- Definition for PHP explode() Function
- Syntax for PHP explode() Function
- Parameter for PHP explode() Function
- Example - Turn a string value to an array
- Example - limit the number of elements in the returned array with a third parameter
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 j av a2 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 j a va 2 s. c om
$fruitString = "apple,pear,banana,strawberry,peach,java2s.com";
$fruitArray = explode( ",", $fruitString, 3 );
print_r($fruitArray);
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP extract() Function
- Syntax for PHP extract() Function
- Parameter for PHP extract() Function
- Example - Convert array to variables
- Example - Use different extract mode
Home » PHP Tutorial » PHP Array Functions