Split PHP array in X equal number of elements

In PHP you can divide an array into an unknown number of chunks by specifying the number of elements in each chunk. To do this you would use the array_chunk function. But what happens when you don’t know the number of elements and just want to split the array in an X number of elements? Unfortunately, we don’t have such a function in PHP but of course, we can create our own function.

In a quick google search, you can find hundreds of solutions, but from my experience, I was unable to find something simple to do the job. Most of them seem to be very complex and vulnerable to bugs.

OK. No more text, here is the function:

function splitMyArray(array $input_array, int $size, $preserve_keys = null): array
{
    $nr = (int)ceil(count($input_array) / $size);
    if ($nr > 0) {
        return array_chunk($input_array, $nr, $preserve_keys);
    }
    return $input_array;
}

Usage:

Suppose that you have this array:

$myArray = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
]

And you want to divide it into 3 parts. Here is how you do it:

splitMyArray($myArray, 3)

The result will be:

[
    0 =>
        [
            0 => 'a',
            1 => 'b',
            2 => 'c',
        ],
    1 =>
        [
            0 => 'd',
            1 => 'e',
            2 => 'f',
        ],
    2 =>
        [
            0 => 'g',
            1 => 'h',
        ],
]

Pretty nice, don’t you think? Easy and simple. As Leonardo da Vinci said: “Simplicity is the ultimate sophistication.”

Note: Make sure that you have enough elements in the array. At least 2 items for each chunk.