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

This guide explains the PHP explode() function, its syntax and parameters, and provides three practical examples showing how to split strings by spaces, commas with a limit, and even into individual characters, helping developers handle text manipulation quickly and clearly.

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 allows you to split a string into an array using a specified separator.

Basic syntax :

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

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

The main purpose of explode() is to return an array where each element is a substring of the original string, separated by the given delimiter.

Example 1: Split a string by spaces

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

Result:

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

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

Example 2: Split by commas with a limit

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

Result:

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

The array contains two elements: the first fruit and the rest combined, demonstrating the $limit parameter.

Example 3: Split a string into individual characters

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

Result:

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 leveraging explode(), developers can easily break strings into arrays for tasks such as text processing, URL parsing, and data extraction, improving code efficiency and readability when used 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.

PHPArraybackend-developmentstring-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.