Search code examples
phparrays

Split a flat array into a predefined number of arrays


I have an array $products which contains a non-fixed number of elements.

I need to split this array into 3 individual arrays. The first two arrays should contain an equal number of elements and the last array may contain less.

So for example if $products contains 16 elements, the output should be:

  • Array 1 contains: 6 elements
  • Array 2 contains: 6 elements
  • Array 3 contains: 4 elements

In the event that there are less than 3 elements in $products, then the relevant arrays need to just return empty.

How can I do this? I tried using array_chunk() but doesn't quite do what I want.

$distributed = array_chunk($products, 3, true);


Solution

  • Just found the answer:

    $distributed = array_chunk($products, (int)ceil(count($products)/3), true);