Skip to content
Tutorials Center
My learning

Topics

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
<?php
print_r(explode(",", "a,b,c"));        // ["a", "b", "c"]
print_r(explode(":", "k:v:w", 2));     // ["k", "v:w"]

Try it

PHP Delimiters and limits

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.

PHP Empty pieces, missing delimiters and errors

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

PHP
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() or preg_split() with PREG_SPLIT_NO_EMPTY.
  • Whitespace is kept. explode(",", "a, b") gives "a" and " b". Trim items with array_map('trim', ...).
  • Multiple delimiters or patterns need preg_split(). For single characters, use str_split().
  • Key-value text such as name=Ada is easy with explode("=", $s, 2); the limit protects values that contain =.
  • Results are strings. Convert to numbers explicitly.
  • CSV with quotes is not for explode(); use str_getcsv().