PHP Reference ยท String Functions
PHP explode() function
Reference for PHP explode(): split a string into an array by a delimiter, use the limit argument including negative values, and avoid empty-string pitfalls.
explode() splits a string wherever a delimiter occurs and returns the pieces as an array. It is the standard way to parse comma-separated values, paths, tags and simple key-value text, and it is the inverse of implode().
The delimiter is a literal string, not a pattern. The optional limit controls how many pieces you get, and a negative limit drops pieces from the end.
<?php print_r(explode(",", "a,b,c")); // ["a", "b", "c"] print_r(explode(":", "k:v:w", 2)); // ["k", "v:w"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
| Name | Description |
|---|---|
$separator |
The delimiter string. Must not be empty. |
$string |
The string to split. |
$limit |
Positive: at most that many elements, the last containing the rest. Zero is treated as 1. Negative: all elements except the last -$limit. |
Return value: an array of strings. If the separator is not found, the array contains the whole string as its only element.
Errors: throws a ValueError if $separator is an empty string.
Usage notes
- Empty input gives
[""], not an empty array. Check for an empty string first when you want zero items. - Adjacent delimiters produce empty strings; they are not collapsed. Use
array_filter()orpreg_split()withPREG_SPLIT_NO_EMPTY. - Whitespace is kept.
explode(",", "a, b")gives"a"and" b". Trim items witharray_map('trim', ...). - Multiple delimiters or patterns need
preg_split(). For single characters, usestr_split(). - Key-value text such as
name=Adais easy withexplode("=", $s, 2); the limit protects values that contain=. - Results are strings. Convert to numbers explicitly.
- CSV with quotes is not for
explode(); usestr_getcsv().
Related
implode(),str_split(),preg_split(),str_getcsv()- Lessons: Strings, String functions