explode()
explode() — Split a string by a string.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator.
Signature
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $separator | string | The boundary string. |
| $string | string | The input string. |
| $limit | int | If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. |
Return value
Returns an array of strings created by splitting the string parameter on boundaries formed by the separator. If separator is an empty string (""), explode() throws a ValueError. If separator contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned. If separator values appear at the start or end of string, said values will be added as an empty array value either in the first or last position of the returned array respectively.
Example
A runnable snippet:
// Example 1 $pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); echo $pieces[0], PHP_EOL; // piece1 echo $pieces[1], PHP_EOL; // piece2 // Example 2 $data = "foo:*:1023:1000::/home/foo:/bin/sh"; list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data); echo $user, PHP_EOL; // foo echo $pass, PHP_EOL; // *
Changelog
| Version | Change |
|---|---|
| 8.0.0 | explode() will now throw ValueError when separator parameter is given an empty string (""). Previously, explode() returned false instead. |
See also
preg_split(), str_split(), mb_split(), str_word_count(), strtok(), implode()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page explode() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.