PHP: Split a string into N evenly sized chunks

Updated: January 10, 2024 By: Guest Contributor Post a comment

Introduction

Sometimes, when working with strings in PHP, you need to break down a large string into smaller, equally sized parts. This can be handy in various scenarios such as when you need to work with large datasets, processing text for display in a user interface, or when sending data over a network in manageable sizes. In this tutorial, we’ll cover several methods to split a string into N evenly sized chunks using PHP.

Before diving in, you should have a fundamental understanding of PHP, including working with strings and arrays. If you’re already familiar with these, let’s proceed. Otherwise, please ensure you brush up on these topics for a better grasp of the concept covered here.

Understanding String Chunking

String chunking, also known as splitting, is the process of breaking a string into smaller strings (chunks) of equal length. In PHP, strings are a sequence of characters and can be manipulated in numerous ways. For our purpose, we will employ the str_split() function to achieve this splitting. This is fine when we want to specify the length of each chunk, but what if we want to specify the number of chunks?

Method 1: Using str_split()

When the chunk size is known, PHP’s built-in str_split() function is the easiest way to split a string:

$string = 'HelloWorld';
$chunkSize = 2;
$chunks = str_split($string, $chunkSize);
print_r($chunks);
// Output: Array ( [0] => He [1] => ll [2] => oW [3] => or [4] => ld )

This method is straightforward, but it doesn’t help when you want N chunks of potentially varying sizes, so we need other approaches.

Method 2: Custom Function Using substr()

Let’s create a custom function to do the chunking:

function split_string_into_chunks($string, $numberOfChunks) {
    $length = mb_strlen($string);
    $chunkSize = ceil($length / $numberOfChunks);
    $chunks = [];

    for ($i = 0; $i < $length; $i += $chunkSize) {
        $chunks[] = mb_substr($string, $i, $chunkSize);
    }

    return $chunks;
}

$string = 'HelloWorld';
$chunks = split_string_into_chunks($string, 3);
print_r($chunks);
// Output: Array ( [0] => Hel [1] => loW [2] => orld )

Here’s how this function works: It determines the chunk size by dividing the string length by the number of chunks and then rounds up using ceil() to ensure we cover the entire string. The function then uses a loop to create the chunks and stores them in an array.

Note that we are using mb_strlen() and mb_substr() instead of strlen() and substr(). This decision ensures that our function is multibyte safe and can handle strings in different character encodings like UTF-8 without issues.

Handling Edge Cases

Although our custom function works well for basic usage, what happens if the string cannot be divided evenly by the number of chunks? We need to handle the remaining characters so that they are distributed as evenly as possible across the resulting chunks.

To address this, we can modify our function:

function split_string_into_chunks($string, $numberOfChunks) {
    // ... [previous code]

    if ($length % $numberOfChunks == 0) {
        return $chunks;
    }

    // Handling uneven chunks
    $excessLength = $length % $chunkSize;
    $excessChunks = array_splice($chunks, -$excessLength);

    for ($i = 0; $i < count($excessChunks); $i++) {
        $chunks[$i] .= $excessChunks[$i];
    }

    return $chunks;
}

After splitting the string, we check if the division is even. If it’s not, we redistribute the remaining characters in the final chunks, ensuring all chunks are as even as possible.

Creating a Responsive Wrapper Function

It might be beneficial to create a function that wraps one or more methods and uses them intelligently based on input:

function adaptive_split_string($string, $numberOfChunks) {
    // If chunks are less than or equal to 1, or greater than the string length
    if ($numberOfChunks <= 1 || $numberOfChunks >= mb_strlen($string)) {
        return str_split($string, mb_strlen($string));
    }
    // Use our custom split_string_into_chunks method
    return split_string_into_chunks($string, $numberOfChunks);
}

This becomes a robust and adaptive approach for varying scenarios.

Final Words

With this tutorial, you should have a solid understanding of how to split a string into N evenly-sized chunks in PHP. Remember that string manipulation is a common operation, and honing your mastery over it will significantly advance your PHP coding expertise.