explode()
The explode()
function takes a string and splits it on a given delimiter string. It returns an array of the substrings produced.
Syntax
explode($delimiter, $string, $limit)
The explode()
function takes three parameters:
$delimiter
: a requiredstring
that specifies the characters on which$string
will be split. The$delimiter
has the following behaviors:- If
$delimiter
is an emptystring
,explode()
will throw aValueError
exception. - If
$delimiter
is not found in$string
and a negative$length
is used, an emptyarray
is returned. - If
$delimiter
is not found in$string
and$length
is positive or omitted, anarray
containing$string
is returned. - If
$delimiter
is found at the start or end of$string
, empty values for each$delimiter
will be added to the beginning or end of the returnedarray
respectively.
- If
$string
: a requiredstring
that will be split by theexplode()
function.$limit
: an optionalint
that specifies how manystrings
will be returned in the resultingarray
as follows:- A positive value will return up to
$limit
strings
if more than$limit
strings
can be produced, splitting on$delimiter
; the last element will contain the remainder of$string
. - A
$limit
of0
is treated as1
. - A negative
$limit
will omit the lastn
elements from the result. - If
$limit
is omitted,explode()
will return as many substrings as possible.
- A positive value will return up to
Example
The following example uses the explode()
function to convert a string
of fruits separated by ", "
to an array
of fruits. Then the print_r()
function prints the information about the returned array
to the console:
<?phpprint_r (explode(", ", "apple, strawberry, orange"));?>
The example will result in the following output:
Array([0] => apple[1] => strawberry[2] => orange)
Codebyte Example
The following shows three examples of the explode()
function operating on one comma-delimited string
.
All contributors
- cslylla58 total contributions
- StevenSwiniarski474 total contributions
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.