0

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);

2
  • 1
    In your example why 6,6,4? What is there that eliminates 7,7,2 or 8,8,0? Can you elaborate on what the goal is/what it is you require? Commented Mar 11, 2014 at 23:27
  • A few sample inputs and the exact desired output would make this question more clear and helpful. The title is a little too vague to be helpful. Commented Jan 19, 2024 at 6:18

1 Answer 1

1

Just found the answer:

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.