Strings7 min readExamples run on PHP 8.5.10

explode()

Learn how PHP explode() splits a string on a separator, how the limit parameter works, and which edge cases and mistakes to watch for.

Signature

explode(string $separator, string $string, int $limit = PHP_INT_MAX): array

Purpose

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 to PHP_INT_MAX, which means no practical limit. The sign of the value changes the behavior:
    • Positive: the array has at most $limit elements, and the last element holds the unsplit remainder of the string.
    • Negative: every piece is returned except the last -$limit pieces.
    • Zero: treated as 1.

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.

Example
<?php
$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;
Output
["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.

Example
<?php
$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;
Output
["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

Example
<?php
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;
}
Output
["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

  1. Swapping the arguments. Writing explode($text, ',') treats your text as the separator. The result is usually a one-element array, or a ValueError if $text happens to be empty.
  2. Using an empty separator to split characters. explode('', $s) throws. To split into single bytes, use str_split(). For multibyte characters, use a multibyte-aware approach such as mb_str_split().
  3. Forgetting about empty elements. Input such as 'a,,b' or a trailing comma produces '' entries. Filter them with array_filter() if they are unwanted, and be careful that the default filter also removes the string '0'.
  4. Expecting trimmed values. explode(',', 'a, b') returns 'a' and ' b'. Apply array_map('trim', ...) or use the separator ', ' when the format is guaranteed.
  5. Assuming numeric types. Every element is a string. Cast values yourself if you need integers.
  6. 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.
  • 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

Destructuring a colon-separated record
<?php
$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;
Output
["foo","1023","","/home/foo","/bin/sh"]
Positive, negative and zero limits
<?php
$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;
Output
["one","two|three|four"]
["one","two","three"]
["one|two|three|four"]
[]
Edge cases: empty pieces, missing separator, empty separator
<?php
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;
}
Output
["a","","b",""]
["",""]
["hello"]
[]
[""]
ValueError