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 after201. 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

Answer

Solution:

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

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

Answer

Solution:

Add additional condition

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

Answer

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

Answer

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

Answer

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

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.