In PHP, the explode()
function is used to split a string into an array based on a specified delimiter. It’s commonly used when you have a string with separators (like commas, spaces, or pipes) and you want to work with the individual pieces.
Syntax
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
- $separator: The boundary string where the split will happen.
- $string: The input string to split.
- $limit (optional): Limits the number of elements in the result.
Basic Example
$text = "apple,banana,orange";
$fruits = explode(",", $text);
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
Example with Space Separator
$sentence = "PHP is a great language";
$words = explode(" ", $sentence);
print_r($words);
Output:
Array
(
[0] => PHP
[1] => is
[2] => a
[3] => great
[4] => language
)
Example with Limit
$data = "one|two|three|four";
$parts = explode("|", $data, 3);
print_r($parts);
Output:
Array
(
[0] => one
[1] => two
[2] => three|four
)
📝 Note: When a limit is specified:
- If positive, it returns at most that many elements, and the last one will contain the rest of the string.
- If negative, it omits that many values from the end of the array.
Negative Limit Example
$data = "red,green,blue,yellow";
$colors = explode(",", $data, -1);
print_r($colors);
Output:
Array
(
[0] => red
[1] => green
[2] => blue
)
Use Case: Convert CSV to Array
$csv = "name,email,phone";
$headers = explode(",", $csv);
print_r($headers);
Output:
Array
(
[0] => name
[1] => email
[2] => phone
)