Split PHP array in X equal number of elements

In PHP you can divide an array in a unknown number of chunks by specifying the number of element 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 a X number of elements? Unfortunately we don’t have such 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 seems 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 in 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.”

Andrew
Member since January 2, 2019

Fullstack Web Developer with more than 12 years of experience in web development. Adept in all stages of advanced web development. Knowledgeable in the user interface, backend, testing, and debugging processes. Bringing forth expertise in design, installation, testing, and maintenance of web systems. Working exclusively and professionally with WordPress since 2010.

Comments

  • Avatar
    Kenneth Isenberg 8 months ago

    Saved as a favorite!, I love your web site!

Avatar

Your email address will not be published. Required fields are marked *