0

I am trying to make an array of arrays. Each array ($group) in the array ($multi_array) needs to be at most 40 items.

$multi_array = array_reduce($items, function($acc, $item) {

  if (count($acc) % 40 === 0) {
    array_push($acc, [$item]);
  } else {
    array_push($acc[count($acc) - 1], $item);
  }

  return $acc;
}, []);

var_dump(count($multi_array));

foreach ($multi_array as $group) {
  var_dump(count($group));
}

However in the first var_dump(count($multi_array)); the value is 1. In the next var_dump the value is 546. I am expecting $rate_limit_array to have at least 13 arrays of length 40. Does anyone know what I am doing wrong inside my reduce function? To achieve my goal, should I take a different approach in PHP?

1 Answer 1

2

Ok I found a different way to do this with array_chunk:

$multi_array = array_chunk($items, 40, true);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.