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

This article explains PHP's explode() function, its syntax and parameters, and provides three practical code examples showing how to split strings by spaces, commas with a limit, and empty strings, highlighting its usefulness for text processing.

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 can split a string by a specified delimiter into an array.

Syntax

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

The function accepts three parameters: $separator (the delimiter), $string (the input string), and an optional $limit that caps the number of returned elements (default is PHP_INT_MAX).

It returns an array containing the substrings.

Example 1: Split by space

$str = "Hello World";
$result = explode(" ", $str);
print_r($result);
Array
(
    [0] => Hello
    [1] => World
)

The string "Hello World" is split into ["Hello", "World"].

Example 2: Split by comma with limit

$str = "apple,banana,orange,grape";
$result = explode(",", $str, 2);
print_r($result);
Array
(
    [0] => apple
    [1] => banana,orange,grape
)

Using a comma as the delimiter and limiting the result to two elements yields ["apple", "banana,orange,grape"].

Example 3: Split by empty string

$str = "Hello";
$result = explode("", $str);
print_r($result);
Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
)

When the delimiter is an empty string, each character becomes a separate array element, resulting in ["H", "e", "l", "l", "o"].

Conclusion

By using explode(), developers can easily split strings according to any delimiter, which is valuable for text handling, URL parsing, and similar tasks, improving code efficiency and readability.

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