PHP 8 reference · String Functions
PHP explode() Function
Split a string into an array by a separator, like turning "a,b,c" into ["a", "b", "c"]. A limit caps the pieces.
PHP 8 Since 4.0
Syntax
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
Parameters
| Parameter | Description |
|---|---|
separator |
The boundary string; it can't be empty. |
string |
The input string. |
limit optional |
Positive: at most this many pieces (the last holds the rest). Negative: drop that many from the end. Default: PHP_INT_MAX |
Return value
An array of strings.
Examples
<?php
print_r(explode(",", "red,green,blue"));
Output
Array
(
[0] => red
[1] => green
[2] => blue
)<?php
[$key, $value] = explode("=", "path=/a=b", 2);
echo "$key -> $value\n";
print_r(explode(".", "a.b.c.d", -1));
Output
path -> /a=b
Array
(
[0] => a
[1] => b
[2] => c
)<?php
print_r(array_map("trim", explode(",", "tea, cake , milk")));
Output
Array
(
[0] => tea
[1] => cake
[2] => milk
)Common mistakes
- The separator comes first:
explode(",", $text), notexplode($text, ","). - An empty string gives
[""], not[]. Check$text === ""first when that matters. - To split on a pattern (any whitespace, several separators) use
preg_split().
Version history
In other languages
str.split()· Pythonstring.split()· JavaScript
Related
implode()· Join array elements into one string with a separator between them. join() is an alias of implode().str_split()· Split a string into an array of chunks of a given length, one byte each by default. Use mb_str_split() for UTF-8.str_getcsv()· Parse one line of CSV text into an array of fields, handling quoted values that contain commas or quotes.- PHP Strings · tutorial