Backend Development 4 min read

Using PHP explode() to Split Strings into Arrays

This article 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 empty strings, illustrating the resulting arrays and typical use cases.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP explode() to Split Strings into Arrays

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

The basic syntax is explode(string $separator, string $string, int $limit = PHP_INT_MAX): array , where $separator is the delimiter, $string is the input string, and $limit optionally limits the number of resulting elements.

The function returns an array containing the substrings obtained after splitting.

Example 1: Splitting a string 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: Splitting by comma with a limit of 2

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

Output:

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

The result is ["apple", "banana,orange,grape"] because the limit restricts the array to two elements.

Example 3: Splitting by an empty string

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

Output:

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

Splitting with an empty string treats each character as a separate element.

Summary

By using explode() , developers can easily divide a string into an array based on a chosen delimiter, which is useful for text processing, URL parsing, and similar tasks, improving code efficiency and readability when applied appropriately.

backendPHParraystring 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

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