Master PHP explode(): Split Strings Efficiently with Real Code Examples

This guide explains PHP's explode() function, its syntax, parameters, and behavior, and provides three practical examples showing how to split strings by spaces, commas with a limit, and empty strings, highlighting the resulting arrays.

php Courses
php Courses
php Courses
Master PHP explode(): Split Strings Efficiently with Real Code Examples

In PHP, strings are a common data type, and the explode() function is used to split a string into an array based on a specified separator.

Function Syntax

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

The function accepts three parameters: $separator – the delimiter. $string – the input string to be split. $limit – optional, limits the number of array elements returned (default is PHP_INT_MAX).

The primary purpose of explode() is to return an array where each element is a substring of the original string, divided by the separator.

Example 1: Split by Space

$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 Limit

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

Output:

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

Here the string is split by commas, but the result is limited to two elements, yielding ["apple", "banana,orange,grape"].

Example 3: Split by Empty String

$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 separator treats each character as a separate element.

Conclusion

By using explode(), developers can easily divide strings into arrays for tasks such as text processing or URL parsing, improving code efficiency and readability when applied appropriately.

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.

PHPArraystring-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.