In this tutorial, you shall learn how to split a string into chunks or substrings of specific length in PHP using str_split() function, with the help of example programs.

PHP – Split String into Chunks of Specific Length

To split a string into chunks of specific length in PHP, use str_split() function.

Call str_split() function and pass the the original string, and the integer representing each chunk length as arguments. The function returns an array of strings.

Syntax

The syntax of str_split() function to split the $input string into chunks of specific length $n is

str_split($input, $n)
ADVERTISEMENT

Examples

1. Split string into chunks of length 3

In this example, we take a string 'abcdefghijklmnop' and split this string into chunks of length 3.

PHP Program

<?php
$input = 'abcdefghijklmnop';
$chunk_length = 3;
$output = str_split($input, $chunk_length);
foreach ($output as $x) {
    echo $x;
    echo '<br>';
}
?>

Output

PHP - Split String into Chunk of Specific Length

Conclusion

In this PHP Tutorial, we learned how to split a string into chunks of specific length, using str_split() function.