How to Use explode() in PHP: Syntax and Examples
In PHP, use the
explode() function to split a string into an array by a specified delimiter. It takes the delimiter and the string as arguments and returns an array of substrings.Syntax
The explode() function splits a string into pieces using a delimiter and returns an array of those pieces.
- delimiter: The character(s) where the string will be split.
- string: The input string to split.
- limit (optional): Maximum number of pieces to return.
php
array explode(string $delimiter, string $string, int $limit = PHP_INT_MAX);Example
This example splits a comma-separated list into an array using a comma as the delimiter and prints the resulting array.
php
<?php $text = "apple,banana,cherry"; $fruits = explode(",", $text); print_r($fruits); ?>
Output
Array
(
[0] => apple
[1] => banana
[2] => cherry
)
Common Pitfalls
Common mistakes include:
- Using an empty string as the delimiter, which causes a warning.
- Expecting
explode()to include the delimiter in the output (it does not). - Not handling the optional
limitparameter correctly, which can affect the number of returned pieces.
php
<?php // Wrong: empty delimiter // $result = explode("", "hello world"); // Warning // Right: use a valid delimiter $result = explode(" ", "hello world"); print_r($result); // Using limit $limited = explode(",", "a,b,c,d", 3); print_r($limited); ?>
Output
Array
(
[0] => hello
[1] => world
)
Array
(
[0] => a
[1] => b
[2] => c,d
)
Quick Reference
| Parameter | Description |
|---|---|
| delimiter | String where the split happens |
| string | Input string to split |
| limit (optional) | Max number of pieces returned |
Key Takeaways
Use explode() to split strings into arrays by a delimiter.
The delimiter cannot be an empty string.
The optional limit controls how many pieces are returned.
explode() does not include the delimiter in the output pieces.
Always check the output array to handle your data correctly.