Signature
explode(string $separator, string $string, int $limit = PHP_INT_MAX): arrayPurpose
explode() breaks a string into an array of substrings. You give it a boundary string, called the separator, and the text to cut up. Every time the separator appears, PHP ends the current piece and starts a new one. It is the standard tool for simple delimited data: comma-separated tags, colon-separated records, path segments, or key/value fragments. The function is binary-safe, so the input may contain any bytes.
Signature
Parameters and defaults
$separator: the boundary string. It can be longer than one character, such as', 'or'::'. It must not be empty.$string: the input text to split.$limit: optional, defaulting toPHP_INT_MAX, which means no practical limit. The sign of the value changes the behavior:- Positive: the array has at most
$limitelements, and the last element holds the unsplit remainder of the string. - Negative: every piece is returned except the last
-$limitpieces. - Zero: treated as
1.
- Positive: the array has at most
The separator always comes first and the string second. Unlike implode(), explode() has never accepted its arguments in either order.
Return value and failure cases
explode() returns an array of strings. If the separator is an empty string, PHP 8 throws a ValueError. Before PHP 8.0 it returned false instead, so old code that checked for false no longer applies.
When the separator does not occur in the string, the result is a one-element array holding the original string. The exception is a negative limit, which in that case produces an empty array.
Example 1: Destructuring a record
A fixed-format record can be split and assigned to variables in one statement. Note that two adjacent separators produce an empty string in the result, not a skipped field.
$line = 'foo:*:1023:1000::/home/foo:/bin/sh';
[$user, $pass, $uid, $gid, $gecos, $home, $shell] = explode(':', $line);
echo json_encode([$user, $uid, $gecos, $home, $shell], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;["foo","1023","","/home/foo","/bin/sh"]
Example 2: Using limit
A positive limit is useful when only the first few fields matter and the rest should stay intact, for example splitting a command from its arguments. A negative limit drops pieces from the end.
$str = 'one|two|three|four';
echo json_encode(explode('|', $str, 2)), PHP_EOL;
echo json_encode(explode('|', $str, -1)), PHP_EOL;
echo json_encode(explode('|', $str, 0)), PHP_EOL;
echo json_encode(explode('|', $str, -4)), PHP_EOL;["one","two|three|four"] ["one","two","three"] ["one|two|three|four"] []
With a limit of 2, the second element contains everything after the first separator. With -1, only the last piece is removed. With 0, the limit behaves like 1, so the whole string comes back as a single element. With -4 on a four-piece string, every piece is removed and the result is empty.
Example 3: Edge cases
echo json_encode(explode(',', 'a,,b,')), PHP_EOL;
echo json_encode(explode(',', ',')), PHP_EOL;
echo json_encode(explode(',', 'hello')), PHP_EOL;
echo json_encode(explode(',', 'hello', -1)), PHP_EOL;
echo json_encode(explode(',', '')), PHP_EOL;
try {
explode('', 'abc');
} catch (ValueError $e) {
echo get_class($e), PHP_EOL;
}["a","","b",""] ["",""] ["hello"] [] [""] ValueError
Leading, trailing and doubled separators all create empty-string elements. An empty input string gives an array with one empty string, not an empty array. That surprises many developers who expect no items for no data.
Common mistakes
- Swapping the arguments. Writing
explode($text, ',')treats your text as the separator. The result is usually a one-element array, or aValueErrorif$texthappens to be empty. - Using an empty separator to split characters.
explode('', $s)throws. To split into single bytes, usestr_split(). For multibyte characters, use a multibyte-aware approach such asmb_str_split(). - Forgetting about empty elements. Input such as
'a,,b'or a trailing comma produces''entries. Filter them witharray_filter()if they are unwanted, and be careful that the default filter also removes the string'0'. - Expecting trimmed values.
explode(',', 'a, b')returns'a'and' b'. Applyarray_map('trim', ...)or use the separator', 'when the format is guaranteed. - Assuming numeric types. Every element is a string. Cast values yourself if you need integers.
- Using it for complex rules. If the delimiter varies, such as any run of whitespace or either a comma or a semicolon, a regular-expression splitter like
preg_split()is a better fit.
Related functions
implode()joins array elements into a string, the inverse operation.str_split()cuts a string into fixed-length chunks.preg_split()splits on a regular expression.mb_split()splits a multibyte string using a regular expression.strtok()tokenizes a string step by step.str_word_count()reports information about the words in a string.
Recap
explode($separator, $string, $limit) splits text on an exact, non-empty separator and returns an array of strings. A positive limit caps the number of pieces and keeps the remainder in the last one, a negative limit removes pieces from the end, and zero acts like one. Adjacent, leading and trailing separators yield empty strings, a missing separator yields the original string in an array, and an empty separator throws a ValueError.
Tested examples
$line = 'foo:*:1023:1000::/home/foo:/bin/sh';
[$user, $pass, $uid, $gid, $gecos, $home, $shell] = explode(':', $line);
echo json_encode([$user, $uid, $gecos, $home, $shell], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;["foo","1023","","/home/foo","/bin/sh"]
$str = 'one|two|three|four';
echo json_encode(explode('|', $str, 2)), PHP_EOL;
echo json_encode(explode('|', $str, -1)), PHP_EOL;
echo json_encode(explode('|', $str, 0)), PHP_EOL;
echo json_encode(explode('|', $str, -4)), PHP_EOL;["one","two|three|four"] ["one","two","three"] ["one|two|three|four"] []
echo json_encode(explode(',', 'a,,b,')), PHP_EOL;
echo json_encode(explode(',', ',')), PHP_EOL;
echo json_encode(explode(',', 'hello')), PHP_EOL;
echo json_encode(explode(',', 'hello', -1)), PHP_EOL;
echo json_encode(explode(',', '')), PHP_EOL;
try {
explode('', 'abc');
} catch (ValueError $e) {
echo get_class($e), PHP_EOL;
}["a","","b",""] ["",""] ["hello"] [] [""] ValueError