# php - Modulus inside loop

800

I have an array that I am looping through and breaking up into chunks of 50. However occasionally the number of items inside that array are more than what fits inside that chunk of 50 ex.:

``````\$array = array(); // has 220 rows

for (\$i = 0; \$i < count(\$array); \$i++) {
\$j[] = \$i;

if (\$i % 50 == 1) {
print_r(\$j); // do something here with the 50 rows
\$j = null;
}
}
``````

The problem here is that this will not print anything after`201`. I know there is some algebraic math involved in solving this but I am drawing a blank. Its times like these where I really wish I had paid attention in math class back in high school.

998

#### Solution:

I think array_chunk fits up your requirement and no maths required.

``````\$result_array = array_chunk(\$array, 50, true);
``````
250

#### Solution:

``````if (\$i % 50 == 1 || count(\$array)-1 == \$i)
``````
939

#### Solution:

You just have to redeclare the array is my guess:

``````\$array = array(); // has 220 rows

for (\$i = 0; \$i < count(\$array); \$i++) {
\$j[] = \$i;

if (\$i % 50 == 1) {
print_r(\$j); // do something here with the 50 rows
\$j = array() ;
}
}
``````

Once you perform`\$j = null` there is no way you can do`\$j[] = \$i`

69

#### Solution:

``````\$array = array(); // has 220 rows

for (\$i = 0; \$i < count(\$array); \$i++) {
\$j[] = \$i;

if (\$i % 50 == 1) {
doSomething(\$j); // do something here with the 50 rows
\$j = array(); // reset the array
}
}
doSomething(\$j); // with the last 20 entries
``````

After your loop is finished, you will have the remaining 201 through 220 entries in`\$j`, so just do your stuff again.

405

#### Solution:

array_chunk might be useful. Basically splits the array into chunks returning a multi dimensional array

People are also looking for solutions to the problem: multiple select option value validating in php

Source