PHP explode() Function
PHP explode() breaks a string into pieces as an array.
PHP explode is a built-in function that split the string based on a certain character or symbol (also called as a delimiter) passed in function parameter and returns an array of strings.
explode ( $separator, $string, $limit )
The explode function accepts three parameters. First two are mandatory and third is optional.
|separator (or delimiter)||Required. Specifies character or string where to break the string|
|string||Required. The input string to break or split|
|limit||Optional. Number of array elements to return|
Note: The “separator” parameter cannot be specified empty string.
This PHP function is useful in following scenarios.
- If you want to divide string based on some character or substring.
- you can extract person names from a string based on spaces.
- If you want to parse a CSV file data that has content separated by a comma.
- you can get the strings by a new line.
Example #1: Split string separated by space
In this example, we have a string containing person names separated by space. Therefore, we can pass space as a delimiter to break the string (names) into the array.
<?php // Take a string containing names with space $message = "Robin Jenny Rocky Mark Deepak"; // Use PHP explode function to separate name by space $names = explode(" ", $message); // print array print_r($names); ?>
Run example: https://paiza.io/projects/gHGN-9ONH_BZJZQjFfHgGg
 => Robin
 => Jenny
 => Rocky
 => Mark
 => Deepak
Example #2: Split string separated by another comma character
In this example, we have a string containing fruits name separated by a comma. Therefore, we can pass a comma character as a delimiter to break the string into the array.
<?php // Take a string containing fruits list separated by a comma $string = "Apple, Banana, Orange, Mango, Grapes"; // Use PHP explode function to separate name by comma $fruits = explode(",", $string); // print array print_r($fruits); ?>
Run example: https://paiza.io/projects/bWkJheKOaINOOsogtVBoPQ
 => Apple
 => Banana
 => Orange
 => Mango
 => Grapes
|Exercises & Assignments|
|No Content Found.|
|Interview Questions & Answers|
|No Content Found.|