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;


Suppose that you have this array:

$myArray = [

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.”

Member since January 2, 2019


  • Avatar
    Kenneth Isenberg 5 months ago

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


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