Skip to content

Commit f443e9f

Browse files
[Edit] PHP: explode() (#7068)
* [Edit] SQL: DATEDIFF() * Update datediff.md * [Edit] PHP: explode() * Update content/php/concepts/string-functions/terms/explode/explode.md ---------
1 parent cacda48 commit f443e9f

File tree

1 file changed

+120
-37
lines changed
  • content/php/concepts/string-functions/terms/explode

1 file changed

+120
-37
lines changed
Lines changed: 120 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,81 +1,164 @@
11
---
22
Title: 'explode()'
3-
Description: 'Splits a given string by a delimiter and returns an array of the substrings produced.'
3+
Description: 'Splits a string into an array based on a specified delimiter'
44
Subjects:
55
- 'Computer Science'
6-
- 'Web Design'
76
- 'Web Development'
87
Tags:
98
- 'Arrays'
10-
- 'Strings'
119
- 'Functions'
10+
- 'Strings'
1211
CatalogContent:
1312
- 'learn-php'
1413
- 'paths/computer-science'
1514
---
1615

17-
The **`explode()`** function takes a string and splits it on a given delimiter string. It returns an array of the substrings produced.
16+
The **`explode()`** function is a built-in PHP [string function](https://www.codecademy.com/resources/docs/php/string-functions) that splits a string into an array based on a specified delimiter. It takes a string and breaks it apart at every occurrence of the delimiter, returning an array containing the resulting substrings. This function is essential for string manipulation and data processing tasks in PHP applications.
17+
18+
The `explode()` function is commonly used in scenarios such as parsing CSV data, processing user input, splitting file paths, extracting words from sentences, and converting delimited strings into manageable array elements. It serves as the counterpart to the [`implode()`](https://www.codecademy.com/resources/docs/php/string-functions/implode) function, which joins array elements into a single string.
1819

1920
## Syntax
2021

2122
```pseudo
22-
explode($delimiter, $string, $limit)
23+
explode(separator, string, limit)
2324
```
2425

25-
The `explode()` function takes three parameters:
26+
**Parameters:**
27+
28+
- `separator`: The delimiter string that specifies where to split the original string. This parameter is required and cannot be an empty string.
29+
- `string`: The input string to be split into an array. This parameter is required.
30+
- `limit`: An optional integer parameter that controls the number of array elements to return. Possible values:
31+
- **Positive integer**: Returns an array with a maximum of `limit` elements, with the last element containing the rest of the string
32+
- **Negative integer**: Returns an array with all elements except for the last `limit` elements
33+
- **Zero**: Returns an array containing one element (the whole string)
34+
- **Not specified**: Returns an array with all possible elements
2635

27-
- `$delimiter`: a required `string` that specifies the characters on which `$string` will be split. The `$delimiter` has the following behaviors:
36+
**Return value:**
2837

29-
- If `$delimiter` is an empty `string`, `explode()` will throw a `ValueError` exception.
30-
- If `$delimiter` is not found in `$string` and a negative `$length` is used, an empty `array` is returned.
31-
- If `$delimiter` is not found in `$string` and `$length` is positive or omitted, an `array` containing `$string` is returned.
32-
- If `$delimiter` is found at the start or end of `$string`, empty values for each `$delimiter` will be added to the beginning or end of the returned `array` respectively.
38+
The `explode()` function returns an array of strings, where each element is a substring of the original string separated by the specified delimiter.
3339

34-
- `$string`: a required `string` that will be split by the `explode()` function.
35-
- `$limit`: an optional `int` that specifies how many `strings` will be returned in the resulting `array` as follows:
40+
## Example 1: Basic String Splitting using `.explode()`
3641

37-
- A positive value will return up to `$limit` `strings` if more than `$limit` `strings` can be produced, splitting on `$delimiter`; the last element will contain the remainder of `$string`.
38-
- A `$limit` of `0` is treated as `1`.
39-
- A negative `$limit` will omit the last `n` elements from the result.
40-
- If `$limit` is omitted, `explode()` will return as many substrings as possible.
42+
This example demonstrates the fundamental usage of `explode()` to split a simple sentence into individual words:
43+
44+
```php
45+
<?php
46+
// Split a sentence into words using space as delimiter
47+
$sentence = "Hello world from PHP programming";
48+
$words = explode(" ", $sentence);
4149

42-
## Example
50+
// Display the resulting array
51+
print_r($words);
52+
?>
53+
```
4354

44-
The following example uses the `explode()` function to convert a `string` of fruits separated by `", "` to an `array` of fruits. Then the `print_r()` function prints the information about the returned `array` to the console:
55+
The output of this code is:
56+
57+
```shell
58+
Array
59+
(
60+
[0] => Hello
61+
[1] => world
62+
[2] => from
63+
[3] => PHP
64+
[4] => programming
65+
)
66+
```
67+
68+
This code splits the sentence at each space character, creating an array where each word becomes a separate element. This is useful for text processing and word analysis tasks.
69+
70+
## Example 2: Processing CSV Data
71+
72+
This example shows how `explode()` can be used to parse comma-separated values, which is common when working with data imports or API responses:
4573

4674
```php
4775
<?php
48-
print_r (explode(", ", "apple, strawberry, orange"));
76+
// Simulate CSV data from a file or API
77+
$csvData = "John,25,Engineer,New York";
78+
$userInfo = explode(",", $csvData);
79+
80+
// Extract individual fields
81+
$name = $userInfo[0];
82+
$age = $userInfo[1];
83+
$profession = $userInfo[2];
84+
$city = $userInfo[3];
85+
86+
// Display parsed information
87+
echo "Name: " . $name . "\n";
88+
echo "Age: " . $age . "\n";
89+
echo "Profession: " . $profession . "\n";
90+
echo "City: " . $city . "\n";
91+
92+
// Alternative: Display the complete array
93+
print_r($userInfo);
4994
?>
5095
```
5196

52-
The example will result in the following output:
97+
This code produces the following output:
5398

5499
```shell
100+
Name: John
101+
Age: 25
102+
Profession: Engineer
103+
City: New York
55104
Array
56105
(
57-
[0] => apple
58-
[1] => strawberry
59-
[2] => orange
106+
[0] => John
107+
[1] => 25
108+
[2] => Engineer
109+
[3] => New York
60110
)
61111
```
62112

63-
## Codebyte Example
113+
This example demonstrates practical data parsing where a single string containing user information is split into manageable components. The `explode()` function makes it easy to access individual data fields for further processing or database storage.
64114

65-
The following shows three examples of the `explode()` function operating on one comma-delimited `string`.
115+
## Codebyte Example: Advanced Usage with Limit Parameter
116+
117+
This example illustrates the power of the limit parameter to control how many array elements are created, which is useful for processing partially structured data:
66118

67119
```codebyte/php
68120
<?php
69-
$str = "list,of,comma,delimited,strings,";
70-
$strarr1 = explode(",", $str);
71-
$strarr2 = explode(",", $str, 5);
72-
$strarr3 = explode(",", $str, -2);
73-
74-
var_dump($strarr1);
75-
echo("<br/>");
76-
var_dump($strarr2);
77-
echo("<br/>");
78-
var_dump($strarr3);
79-
echo("<br/>");
121+
// URL path processing with different limit values
122+
$urlPath = "/category/subcategory/product/details/reviews";
123+
124+
// Split with positive limit - get first 3 parts only
125+
$limitedSplit = explode("/", $urlPath, 3);
126+
echo "With limit 3:\n";
127+
print_r($limitedSplit);
128+
129+
// Split with negative limit - exclude last 2 parts
130+
$negativeLimitSplit = explode("/", $urlPath, -2);
131+
echo "With limit -2:\n";
132+
print_r($negativeLimitSplit);
133+
134+
// Split without limit - get all parts
135+
$fullSplit = explode("/", $urlPath);
136+
echo "Without limit:\n";
137+
print_r($fullSplit);
138+
139+
// Practical example: Extract domain parts
140+
$email = "[email protected]";
141+
$emailParts = explode("@", $email, 2);
142+
$username = $emailParts[0];
143+
$domain = $emailParts[1];
144+
145+
echo "Username: " . $username . "\n";
146+
echo "Domain: " . $domain . "\n";
80147
?>
81148
```
149+
150+
This example shows how the limit parameter provides fine-grained control over string splitting. A positive limit creates a maximum number of elements, a negative limit excludes elements from the end, and the practical email example shows how limiting can prevent over-splitting when you only need specific parts.
151+
152+
## Frequently Asked Questions
153+
154+
### 1. What is the difference between `implode()` and `explode()`?
155+
156+
The `explode()` function splits a string into an array using a delimiter, while `implode()` does the opposite by joining array elements into a single string using a specified separator. They are complementary functions for string and array conversion.
157+
158+
### 2. Can the separator parameter be an empty string?
159+
160+
No, the separator parameter cannot be an empty string. PHP will generate a warning if you attempt to use an empty separator. Use alternative string functions like `str_split()` if you need to split a string into individual characters.
161+
162+
### 3. What happens if the delimiter is not found in the string?
163+
164+
If the delimiter is not found in the string, `explode()` returns an array containing the original string as the single element. No splitting occurs, and the function doesn't generate an error.

0 commit comments

Comments
 (0)