Master PHP’s str_split(): Split Strings into Characters Easily
Learn how to use PHP’s str_split() function to divide strings into individual characters or custom-sized chunks, with clear syntax explanations, practical examples—including splitting “Hello World” and generating numeric codes—plus tips for handling default and optional parameters.
In PHP programming, handling strings often requires processing characters, and the basic unit of string manipulation is the character. The str_split() function helps split a string into individual characters.
Function Usage
The function format is:
<code>str_split ( string $string [, int $split_length = 1 ] )</code>The first parameter is the required string to split. The optional second parameter specifies the length of each chunk, defaulting to 1.
The function returns an array containing the split string chunks.
Example with Custom Chunk Length
Using the second parameter, you can set the length of each chunk. The following code splits a string into chunks of length 2:
<code>$string = "Hello World";
$split_arr = str_split($string, 2);
print_r($split_arr);
</code>The resulting array is ["He", "ll", "o ", "Wo", "rl", "d"].
Example with Default Chunk Length
If the second parameter is omitted, the default chunk length is 1. The code below splits "Hello World" into individual characters:
<code>$string = "Hello World";
$split_arr = str_split($string);
print_r($split_arr);
</code>The output array contains ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'].
Generating a Numeric Code
In scenarios like generating random numbers or passwords, you may need a string of a specific length. The following example creates a 6‑digit numeric string:
<code>$char_arr = range(0, 9);
shuffle($char_arr);
$code_arr = array_slice($char_arr, 0, 6);
$code = implode("", $code_arr);
print("Generated code: " . $code);
</code>Summary
The str_split() function allows quick string splitting with flexible chunk lengths. By passing the target string as the first argument and optionally specifying the chunk size, you can easily obtain arrays of characters or substrings, a common need in PHP development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.