PHP Tutorial - 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//  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.





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
$fruitString = "apple,pear,banana,strawberry,peach,java2s.com"; 
$fruitArray = explode( ",", $fruitString, 3 );   
print_r($fruitArray);
?>

The code above generates the following result.

Example 3

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.