PHP explode() Function

Split a string into an array by a delimiter

Try explode() - edit and run
Output
Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
)

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 $limit elements, 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 a ValueError in PHP 8. Use str_split() to split into characters.
  • Empty string: explode(",", "") returns [""] (one empty element), not an empty array.
  • Real CSV: for quoted fields like "a,b",c use str_getcsv() instead of explode().

PHP explode() FAQ

How do I split a string by multiple delimiters?

Use preg_split('/[,;|]/', $string), which accepts a regular expression as the separator.

How do I remove empty elements after explode()?

Wrap it in array_filter(): array_filter(explode(",", $s), 'strlen') keeps "0" but drops empty strings.

What is the opposite of explode()?

implode() (alias join()) joins array elements back into a string.