PHP explode() Function

PHP explode() breaks a string into pieces and returns them as an array. You tell the function where to cut the string by giving a separator (also called delimiter), like a comma or a space.


Syntax

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

Parameters

ParameterDescription
separatorRequired. The character or text where to split the string. It can not be an empty string
stringRequired. The string that you want to split
limitOptional. Maximum number of array elements. A positive number keeps the rest of the string in the last element. A negative number removes that many elements from the end

Return value: an array of strings. If the separator is not found, you get an array with the whole string as the only element.


Examples

Example #1: Split a string by space

<?php
$message = "Robin Jenny Rocky Mark Deepak";

$names = explode(" ", $message);

print_r($names);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => Robin
[1] => Jenny
[2] => Rocky
[3] => Mark
[4] => Deepak
)


Example #2: Split by comma

Notice that the space after each comma stays with the value. Use trim() if you do not want it.

<?php
$string = "Apple, Banana, Orange";

$fruits = explode(",", $string);
print_r($fruits);

print_r(array_map("trim", $fruits));
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => Apple
[1] => Banana
[2] => Orange
)
Array
(
[0] => Apple
[1] => Banana
[2] => Orange
)


Example #3: Use the limit parameter

<?php
$text = "one-two-three-four";

print_r(explode("-", $text, 2));
print_r(explode("-", $text, -1));
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => one
[1] => two-three-four
)
Array
(
[0] => one
[1] => two
[2] => three
)

With limit 2, the array has only two elements, and the second one has the rest. With limit -1, the last element is removed.


Common uses

  • Get the first and last name from a full name.
  • Read values of a CSV line (for real CSV files use str_getcsv() or fgetcsv(), because they handle quotes).
  • Get the domain from an email: explode("@", $email)[1].
  • Split a text by new lines.
Note: To join an array back into a string, use implode(). Learn the difference in explode() vs implode().

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.