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;


Suppose that you have this array:

$myArray = [

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.

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.


  • Kenneth Isenberg 2 years ago

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

Cancel reply

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