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

ParameterIs RequiredDescription
separatorRequired.Separator to break the string
stringRequired.String to split
limitOptional.Number of array elements to return.

Possible values for limit:

ReturnMeaning
> 0Returns an array with a maximum of limit element(s)
< 0Returns an array except for the last -limit elements()
0Returns 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.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions