PHP explode() Function

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Functions

What You’ll Learn

The explode() function splits a string into an array of pieces wherever a delimiter appears. It is one of the most-used PHP functions for parsing CSV data, URLs, tags, and any text separated by a known character or substring.

01

String → Array

Split by delimiter.

02

Separator First

Before the string.

03

Limit Param

Cap array elements.

04

implode() Pair

Inverse operation.

05

CSV & URLs

Parse structured text.

06

Binary Safe

Works on any bytes.

Definition and Usage

In PHP, explode() breaks a string at every occurrence of a separator and returns the pieces as an indexed array. The separator itself is removed from the results. If the separator is not found, you get a one-element array containing the original string.

💡
Beginner Tip

Remember the argument order: explode($separator, $string)—delimiter first, string second. This is the opposite of how many beginners guess. Pair it with implode() to join arrays back into strings.

📝 Syntax

The explode() function accepts a separator, a string, and an optional limit:

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

Parameters

  • $separator — the boundary string to split on (e.g. ",", " ", "|"). Cannot be empty in PHP 8+.
  • $string — the input string to split.
  • $limit (optional) — maximum number of elements returned. Positive: last element holds the remainder. Negative: excludes elements from the end.

Return Value

Returns an array of strings. An empty input string returns [""] (one empty element), not an empty array.

⚡ Quick Reference

Split
explode(",", $csv)

Comma-separated values

Words
explode(" ", $sentence)

Split on spaces

Limit
explode("|", $s, 2)

Max 2 elements

Join back
implode(",", $parts)

Reverse of explode

Examples Gallery

Run these examples in PHP 7+. Each demonstrates a common pattern beginners encounter with explode().

📚 Getting Started

Split strings on common delimiters.

Example 1 — Split a Comma-Separated List

The classic use case: turn a delimited string into an array you can loop over.

PHP
<?php
$string = "apple,orange,banana";
$fruits = explode(",", $string);

print_r($fruits);

foreach ($fruits as $fruit) {
    echo "- $fruit\n";
}
?>

How It Works

Each comma triggers a split. The delimiter is not included in the result. Three fruits produce a three-element array indexed from 0.

Example 2 — Split with a Positive Limit

A positive limit caps how many array elements are returned. The last element contains everything after the final split point.

PHP
<?php
$sentence = "Hello World";
$parts    = explode(" ", $sentence, 2);

print_r($parts);

$str = "one|two|three|four";
print_r(explode("|", $str, 2));
?>

How It Works

With limit 2, only two elements are returned. Remaining delimiters stay inside the last element—useful when splitting key=value&foo=bar where values may contain the delimiter.

📈 Practical Patterns

Negative limits, real-world parsing, and implode pairing.

Example 3 — Negative Limit (PHP Manual Pattern)

A negative limit excludes elements from the end of the array instead of capping from the start.

PHP
<?php
$str = "one|two|three|four";

echo "No limit:\n";
print_r(explode("|", $str));

echo "Limit -1 (drop last element):\n";
print_r(explode("|", $str, -1));

echo "Delimiter not found:\n";
print_r(explode(",", "hello"));
?>

How It Works

When the delimiter is missing, the whole string becomes a single array element. Negative limits are handy when you want “everything except the last N parts.”

Example 4 — Parse Structured Data (URL Path & Query)

Real applications use explode() to break apart paths, tags, and configuration strings.

PHP
<?php
// Split a URL path into segments
$path    = "articles/42/show";
$segments = explode("/", $path);
echo "Segments: " . implode(" | ", $segments) . "\n";

// Parse key=value pairs from a query string
$query   = "name=Alice&role=editor&active=1";
$pairs   = explode("&", $query);

foreach ($pairs as $pair) {
    [$key, $value] = explode("=", $pair, 2);
    echo "$key => $value\n";
}
?>

How It Works

Using limit 2 on explode("=", $pair) ensures values containing = stay intact. For production URL parsing, consider parse_str() instead.

Example 5 — explode() and implode() Round-Trip

implode() is the inverse of explode()—join array elements back into a string.

PHP
<?php
$original = "red,green,blue,yellow";
$delimiter = ",";

$parts   = explode($delimiter, $original);
$rebuilt = implode($delimiter, $parts);

echo "Original: $original\n";
echo "Parts:    " . count($parts) . " items\n";
echo "Rebuilt:  $rebuilt\n";
echo "Match:    " . ($rebuilt === $original ? "yes\n" : "no\n");

// Change delimiter on rebuild
echo "Pipe-delimited: " . implode("|", $parts) . "\n";
?>

How It Works

Split with one delimiter, join with another—implode() does not care what delimiter was used to create the array. Both functions are binary-safe.

🚀 Common Use Cases

  • CSV and list parsing — split comma-, pipe-, or tab-separated values into arrays.
  • URL and path segments — break /articles/42/show into route parts.
  • Query string handling — split key=value pairs (use parse_str() for full URLs).
  • Tag and keyword lists — convert php,html,css into individual tags.
  • Log file parsing — split lines on delimiters for analysis.

🧠 How explode() Works

1

PHP scans for the separator

You provide a delimiter string and the input text. PHP finds every occurrence of the separator.

Input
2

String is cut into pieces

Each segment between separators becomes an array element. The separator itself is discarded.

Transform
3

Limit adjusts the result

If a limit is set, PHP stops splitting early (positive) or drops trailing elements (negative).

Output
=

Indexed array

Ready to loop, filter, or rejoin with implode().

📝 Notes

  • Argument order is explode($separator, $string)—separator first, always.
  • An empty separator throws ValueError in PHP 8+ (use str_split() for character arrays).
  • An empty input string returns [""], not an empty array.
  • Leading or trailing separators produce empty string elements at the start or end.
  • For complex patterns (regex), use preg_split() instead of explode().

Conclusion

The explode() function is essential for turning delimited strings into workable arrays. Master the separator, string, and limit parameters, and pair it with implode() whenever you need to join data back together.

For simple splits, explode() is fast and readable. Reach for preg_split() when you need regular expressions, or dedicated functions like parse_str() for full query strings.

💡 Best Practices

✅ Do

  • Put the separator argument first: explode(",", $s)
  • Use limit 2 when values may contain the delimiter
  • Trim whitespace from parts if needed: array_map('trim', $parts)
  • Use implode() to rejoin arrays into strings
  • Validate empty strings before assuming an empty array

❌ Don’t

  • Pass an empty string as the separator (PHP 8+ error)
  • Swap argument order like explode($string, ",")
  • Use explode for complex regex-based splitting
  • Assume explode('/', '') returns an empty array
  • Parse full URLs with explode alone—use parse_url()

Key Takeaways

Knowledge Unlocked

Five things to remember about explode()

Use these points whenever you split strings in PHP.

5
Core concepts
📈 02

Separator First

Before the string.

Syntax
🛠 03

Limit Param

Positive or negative.

Advanced
🔄 04

implode() Pair

Join back to string.

Companion
05

Not Found

One-element array.

Behavior

❓ Frequently Asked Questions

explode() splits a string into an array of substrings using a delimiter (separator). Each time the delimiter appears in the string, a new array element begins.
array explode(string $separator, string $string, int $limit = PHP_INT_MAX). Note the order: separator comes first, then the string—unlike implode(), which accepts arguments in either order.
explode() returns an array with one element containing the entire original string. For example, explode(',', 'hello') returns ['hello'].
A positive limit caps the number of array elements—the last element holds any remaining text. A negative limit excludes that many elements from the end. A limit of zero is treated as one.
No. Since PHP 8.0, an empty separator throws a ValueError. Use str_split() if you need to split a string into individual characters.
explode() splits a string into an array (string → array). implode() joins array elements into a string (array → string). They are inverse operations.

Explore More PHP String Functions

Continue with fprintf(), htmlspecialchars(), and the rest of the string function reference.

Next: fprintf() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful