01 · THE IDEAREAD → TRY → LEARN
Why split strings?
A lot of real data arrives as one string: a comma-separated list of tags, a path-like value, or a pipe-delimited record. Before you can validate or count the pieces, you need an array. PHP's basic tool for this is explode(), and its partner for the return trip is implode().
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
The separator comes first, then the text. explode() cuts the text at every occurrence of the separator and returns the pieces as a list of strings. The separator is a literal string, not a pattern, so characters like | or . have no special meaning.
A first round trip
Split a string, look at the array, then join it back with a different glue string.
$parts = explode(',', 'red,green,blue');
echo json_encode($parts), PHP_EOL;
echo implode(' / ', $parts), PHP_EOL;["red","green","blue"] red / green / blue
The array holds three strings, and implode() places the glue only between elements, never at the ends. Splitting and joining are not always perfect inverses, though. If you split on one delimiter and join with another, you have deliberately changed the format.
Controlling the result with limit
The optional third argument decides how many pieces you get:
- A positive limit returns at most that many elements, and the last element holds the unsplit remainder.
- A negative limit drops that many components from the end.
- A limit of zero is treated as 1.
This is useful when only the first delimiter matters, such as a key=value pair where the value may itself contain an equals sign.
$text = 'one|two|three|four';
echo json_encode(explode('|', $text, 2)), PHP_EOL;
echo json_encode(explode('|', $text, -1)), PHP_EOL;
echo json_encode(explode('|', '')), PHP_EOL;["one","two|three|four"] ["one","two","three"] [""]
The last line is an important surprise: splitting an empty string does not give an empty array. It gives an array with one empty string, because the text contains zero separators and therefore one piece.
Edge cases to remember
- If the separator does not appear, you get a one-element array holding the original string.
- A separator at the start or end produces an empty string in the first or last position. Two separators in a row produce an empty string between them.
- An empty separator (
"") throws aValueErrorin PHP 8. Check it first if the separator comes from user input. explode()is binary-safe, and it does not trim whitespace for you."a, b"split on a comma gives"a"and" b".
Worked example: cleaning a tag list
Users type tag lists with uneven spacing and stray commas, such as ' php, ,web,, code '. A tidy function needs four steps: split on the comma, trim each piece, discard pieces that are empty, and renumber the array so it is a proper list.
function cleanTags(string $input): array {
$parts = array_map('trim', explode(',', $input));
$nonEmpty = array_filter($parts, fn(string $part): bool => $part !== '');
return array_values($nonEmpty);
}
echo json_encode(cleanTags(' php, ,web,, code ')), PHP_EOL;["php","web","code"]
The array_values() call matters. array_filter() keeps the original keys, so after removing items you may be left with keys such as 1 and 3. Encoded as JSON, that array becomes an object instead of a list. Re-indexing keeps the result predictable for callers and tests.
Notice the strict comparison with an empty string. A looser check such as !empty($part) would also discard the string "0", which can be legitimate data.
Exercise contract
Write a function named cleanTagList that takes one string argument and returns an array of strings.
- Split the input on commas.
- Trim whitespace from each piece.
- Remove pieces that are empty after trimming.
- Return a re-indexed list in the original order.
An empty input, or input made only of commas and spaces, must return an empty array. Input without any comma returns a single trimmed tag. Your function is checked against five inputs, including the empty string and a string with leading, trailing and doubled commas. Compare the returned arrays, not printed output.
Recap
explode() splits on a literal separator, limit shapes the result, and implode() joins with glue. Remember that an empty string splits into [""], that nothing is trimmed automatically, and that filtering requires re-indexing when you need a list.
Functions · Arrays · Types
- Convert delimited text to arrays and back
- Implement and test a deterministic PHP 8.4 function