What does explode() do?
explode() breaks a string into an array of substrings wherever $separator occurs. It is the opposite of implode().
Syntax
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
Parameters
$separator- The boundary string. It cannot be empty.$string- The string to split.$limit- Positive: at most$limitelements, the last one containing the rest of the string. Negative: all elements except the last-$limit. Zero is treated as 1.
Return value
An array of strings. If the separator is not found, the array contains the whole string as its only element.
explode() examples
Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.
1. Split a comma-separated list
<?php
$csv = "apple,banana,cherry";
$fruits = explode(",", $csv);
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => banana
[2] => cherry
)
2. Using the limit parameter
<?php
$str = "one,two,three,four";
print_r(explode(",", $str, 2));
print_r(explode(",", $str, -1));
Output:
Array
(
[0] => one
[1] => two,three,four
)
Array
(
[0] => one
[1] => two
[2] => three
)
3. Trim the pieces and destructure the result
<?php
$input = "red, green , blue";
$colors = array_map('trim', explode(",", $input));
print_r($colors);
[$user, $domain] = explode("@", "[email protected]");
echo "User: $user, Domain: $domain\n";
Output:
Array
(
[0] => red
[1] => green
[2] => blue
)
User: alice, Domain: example.com
Common mistakes and gotchas
- Empty separator:
explode("", $s)throws aValueErrorin PHP 8. Usestr_split()to split into characters. - Empty string:
explode(",", "")returns[""](one empty element), not an empty array. - Real CSV: for quoted fields like
"a,b",cusestr_getcsv()instead ofexplode().