Backend Development 4 min read

Using PHP str_split() to Split Strings into Characters

This article explains the PHP str_split() function, its syntax, parameters, return value, and provides multiple code examples showing how to split a string into characters or fixed‑length chunks and even generate numeric codes for use cases like verification codes.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP str_split() to Split Strings into Characters

In PHP programming, handling strings often requires breaking them into individual characters, and the str_split() function provides a simple way to achieve this.

Function usage

The function signature is:

str_split ( string $string [, int $split_length = 1 ] )

The first argument is the required string to be split. The optional second argument specifies the length of each chunk; if omitted, the default length is 1.

The function returns an array containing the split string segments.

Example with custom chunk length

The following code splits the string "Hello World" into two‑character pieces:

$string = "Hello World";
$split_arr = str_split($string, 2);
print_r($split_arr);

Resulting array: ["He", "ll", "o ", "Wo", "rl", "d"].

Example with default chunk length

When the second parameter is omitted, each character becomes a separate element:

$string = "Hello World";
$split_arr = str_split($string);
print_r($split_arr);

Resulting array: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'].

Practical use case – generating a numeric verification code

The code below creates a six‑digit random numeric string, which can be used as a simple captcha or verification code:

$char_arr = range(0, 9);
shuffle($char_arr);
$code_arr = array_slice($char_arr, 0, 6);
$code = implode("", $code_arr);
print("生成的验证码为:$code");

Summary

The str_split() function is a convenient tool for quickly dividing a string into chunks of any length; you only need to pass the target string as the first argument. It is frequently used in PHP development for tasks such as character analysis, data parsing, and generating random codes.

Backend DevelopmentPHPCode Examplestring-manipulationstr_split
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.