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:
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);
Just found the answer:
$distributed = array_chunk($products, (int)ceil(count($products)/3), true);