DEV Community

Cover image for How-to split a number into equal chunks
Latz
Latz

Posted on

How-to split a number into equal chunks

The other day I had to iterate over a large number of items but to avoid a timeout I could only compute a certain amount at a time. So I had to split the number into equal chunks and a remainder. Here’s an easy way to determine the chunk size:
$totalNumber = 50321;
$chunkSize = 1023;
$remainder = $totalNumber % $chunkSize;
$chunks = ($totalNumber - $remainder) / $chunkSize;

The code return the following values:
$remainder => 194
$chunks => 49
Verification: (49 * 1023) + 194 = 50321

How does it work?
In line 5 $totalNumber is divided by a modulo operator (“%” is the PHP token for modulo). The operator returns the remainder of the division (194). By subtracting this value from $totalNumber it becomes a whole number multiple of $chunks and the division with $chunkSize equals the desired number of $chunks (line 6).
Now you have the number of necessary iterations and the remaining part.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay