Using PHP explode() to Split Strings: Syntax, Parameters, and Practical Examples

This article explains PHP's explode() function, detailing its syntax, parameters, and return value, and provides three practical code examples that demonstrate splitting strings by spaces, commas with a limit, and empty strings to obtain character arrays.

php Courses
php Courses
php Courses
Using PHP explode() to Split Strings: Syntax, Parameters, and Practical Examples

In PHP, strings are a common data type, and the explode() function can be used to split a string by a specified delimiter.

The basic syntax of explode() is:

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

The function accepts three parameters: $separator (the delimiter), $string (the string to split), and optional $limit (maximum number of array elements, default PHP_INT_MAX).

The function returns an array containing the substrings.

Example 1: Split a string by space

Code:

$str = "Hello World";
$result = explode(" ", $str);
print_r($result);

Output:

Array
(
    [0] => Hello
    [1] => World
)

This splits "Hello World" into ["Hello", "World"].

Example 2: Split by comma with element limit

Code:

$str = "apple,banana,orange,grape";
$result = explode(",", $str, 2);
print_r($result);

Output:

Array
(
    [0] => apple
    [1] => banana,orange,grape
)

This splits the string into two elements: ["apple", "banana,orange,grape"].

Example 3: Split by empty string (character by character)

Code:

$str = "Hello";
$result = explode("", $str);
print_r($result);

Output:

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
)

Using an empty string as the delimiter splits the string into individual characters.

Conclusion

By using explode(), you can easily split strings into arrays, which is useful for text processing, URL parsing, and more; proper use improves code efficiency and readability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentPHPCode Examplesstring-splittingexplode
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.