Definition and Usage
The explode()
function splits a string into an array based on a custom delimiter.
$fruits = explode(',', 'apple,banana,cherry');
print_r($fruits);
/* Output:
Array
(
[0] => apple
[1] => banana
[2] => cherry
)
*/
In this example, the string 'apple,banana,cherry'
is split by a custom delimiter, the comma ','
, and the result is returned as an array containing each fruit name as a separate element.
The explode()
function is especially useful for splitting strings by a delimiter and converting them into arrays for further processing.
Syntax
explode(string $delimiter, string $string, int $limit = PHP_INT_MAX): array
Parameters
$delimiter |
The delimiter string used to split the input string. |
---|---|
$string |
The original string to be split. |
$limit |
The maximum number of elements to return. If omitted, the string will be split by the delimiter without limit. |
Return Values
The explode()
function splits a string by a specified delimiter and returns the resulting array.
Relationship Between Parameters and Return Values
Let's examine how the parameters affect the return values
When the Delimiter is an Empty String (''
)
- Before PHP 8.0.0, providing an empty string (
''
) as the delimiter causedexplode()
to returnfalse
. - Since PHP 8.0.0, passing an empty string as the delimiter throws a
ValueError
.
// Example before PHP 8.0.0
$sentence = 'Hello! Welcome!';
$words_array = explode('', $sentence);
var_dump($words_array); // bool(false)
Note:
Using an empty string (''
) as the delimiter may also trigger a warning depending on your PHP configuration.
When the Delimiter Appears at the Start or End of the Original String
If the delimiter specified by $delimiter
appears at the beginning or end of the original string, the returned array will accordingly start or end with empty strings.
$sentence = ',Hello! Welcome!';
$words_array = explode(',', $sentence);
var_dump($words_array);
// array(2) { [0]=> string(0) "" [1]=> string(14) "Hello! Welcome!" }
$sentence = 'Hello! Welcome!,';
$words_array = explode(',', $sentence);
var_dump($words_array);
// array(2) { [0]=> string(14) "Hello! Welcome!" [1]=> string(0) "" }
$sentence = ',Hello! Welcome!,';
$words_array = explode(',', $sentence);
var_dump($words_array);
// array(3) { [0]=> string(0) "" [1]=> string(14) "Hello! Welcome!" [2]=> string(0) "" }
When the Delimiter is the Same as the Original String
If the delimiter matches the entire string, the returned array contains two empty strings.
$sentence = 'Hello';
$words_array = explode('Hello', $sentence);
var_dump($words_array);
// array(2) { [0]=> string(0) "" [1]=> string(0) "" }
Precautions
- Check for the delimiter: Before using the
explode()
function, it's recommended to verify whether the string contains the specified delimiter. If the delimiter is not found,explode()
will return the original string as a single-element array, so caution is needed. - Handling whitespace: Be careful when the string has whitespace at the beginning or end. If the delimiter appears next to whitespace, the first or last array element may include that whitespace.
- Handling consecutive delimiters: If delimiters appear consecutively, empty strings may be added to the resulting array. This can lead to dealing with empty values, so attention is necessary.
- Case sensitivity: The
explode()
function is case-sensitive. The delimiter must exactly match the case in the string to split correctly. - Length of the delimiter: The
explode()
function requires an exact delimiter. For example, to split by a space character, you must explicitly specifyexplode(' ', $string)
. - Memory usage: When handling large strings,
explode()
can impact memory consumption. For very large strings, consider alternative methods to optimize memory usage.
Practical Examples
The following examples demonstrate how the explode()
function behaves in various scenarios.
Splitting a String
Using the explode()
function, let's split the following string into an array using the pipe character (|
) as the delimiter.
$input_string = 'apple|banana|cherry';
$delimiter = '|';
$fruits_array = explode($delimiter, $input_string);
print_r($fruits_array);
/* Output:
Array
(
[0] => apple
[1] => banana
[2] => cherry
)
*/
In the code above, the explode()
function splits $input_string
using the pipe (|
) delimiter into an array.
URL Parsing
As an example, consider extracting the path and query parameters from a URL.
$url = 'https://www.example.com/products?category=electronics&page=1';
$parts = explode('?', $url);
$path = $parts[0];
$query_string = $parts[1];
echo "Path: $path"; // Output: 'Path: https://www.example.com/products'
echo "Query String: $query_string"; // Output: 'Query String: category=electronics&page=1'
In the code above, the explode()
function splits the URL at the question mark (?
), separating the path from the query string.
Note:
This example assumes the query string in the URL is not URL-encoded. In real-world applications, it is common to encode URL query strings for safety, and when splitting such URLs, you would typically decode the query string afterward.
Note:
PHP provides built-in functions for parsing URL components. The parse_url()
function parses a URL string and returns its components.
String Parsing
Another example is extracting time units from a time string.
For instance, consider a time string formatted as 02:30:45
, representing hours, minutes, and seconds. We want to extract each time unit.
$time = '02:30:45';
$timeParts = explode(':', $time);
$hours = $timeParts[0];
echo "Hours: $hours"; // Output: 'Hours: 02'
Here, the explode()
function splits the string by the colon (:
) delimiter into an array. The first element of the resulting array represents the hours. Therefore, the output will be "Hours: 02". This example can be extended to extract minutes and seconds or perform more complex time format parsing.