PHP 8 reference · String Functions

PHP explode() Function

Split a string into an array by a separator, like turning "a,b,c" into ["a", "b", "c"]. A limit caps the pieces.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

explode(string $separator, string $string, int $limit = PHP_INT_MAX): array

Parameters

ParameterDescription
separator The boundary string; it can't be empty.
string The input string.
limit optional Positive: at most this many pieces (the last holds the rest). Negative: drop that many from the end. Default: PHP_INT_MAX

Return value

An array of strings.

Examples

Split by a commaTry it yourself
<?php
print_r(explode(",", "red,green,blue"));

Output

Array
(
    [0] => red
    [1] => green
    [2] => blue
)
Limit the piecesTry it yourself
<?php
[$key, $value] = explode("=", "path=/a=b", 2);
echo "$key -> $value\n";
print_r(explode(".", "a.b.c.d", -1));

Output

path -> /a=b
Array
(
    [0] => a
    [1] => b
    [2] => c
)
Trim each pieceTry it yourself
<?php
print_r(array_map("trim", explode(",", "tea, cake , milk")));

Output

Array
(
    [0] => tea
    [1] => cake
    [2] => milk
)

Common mistakes

  • The separator comes first: explode(",", $text), not explode($text, ",").
  • An empty string gives [""], not []. Check $text === "" first when that matters.
  • To split on a pattern (any whitespace, several separators) use preg_split().

Version history

VersionChange
PHP 4.0Added
PHP 8.0An empty separator throws a ValueError instead of returning false.

In other languages

Was this page helpful?