Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php if iterator divisible by statement for dynamic columns

Tags:

iterator

php

math

Im trying to make dynamic column list that will be 4 columns total (PHP). Im echoing an array and after every time 4 array items are echod, I would like to wrap those 4 array items in a div called "column".

So basically, I thought I could do this with a self counting $i++ statement, but first off I'm having trouble starting the count from anything but zero (I tried setting the variable initially outside of the for each loop.)

Anyways, ya, if you could kindly show me how to check to see if the $++ is divisible by 4 in php, so that I can insert a if $i++ is divisible by 4 then echo "" , it would be much appreciated. But first I believe I need to figure out how to start the counting at 1 (so that the if $i++ is divisible by 4 would work... right??)

like image 568
thrice801 Avatar asked Dec 03 '22 12:12

thrice801


2 Answers

If you divide by 4 it will be integer division and the quotient will be the factor of 4. What you probably want is the modulus operator %. It will give you the remainder. So when $i is a multiple of 4 it will be 0.

if (($i % 4) == 0) {
  // evenly divisible by 4 logic
}

Modulus can be inefficient. Since you are dividing by a multiple of 2, you could shift bits right by 2. It is the same as dividing by 4 and much more efficient. Check out bit shifting.

like image 114
Jason McCreary Avatar answered Feb 16 '23 01:02

Jason McCreary


% is the modulus operator. It returns the remainder after a division, so 7 % 4 == 3.

You really should start from 0. This is because 0 % 4 == 0 and 4 % 4 == 0... AND you want the very first item to be a new row! So you want new rows on 0, 4, 8, etc... If you start at one, then 1, 2, and 3 would not be in a row.

Additionally, we have to remember to close the row on every item one before a new row.

Finally, if we exit our loop without closing the final row, we have to do that after we have exited the loop.

I'll show how to do this with tables, but you can use divs with classes just as easilly.

<table>
    <?php
    // Start at zero, so we start with a new row
    // Since we start at 0, we have to use < number of items, not <=
    for ($i = 0; $i < $numberOfItems; ++$i)
    {
        // if divisible by 0 start new row
        if ($i % 4 == 0)
            echo '<tr>';
        // Always print out the current item
        echo '<td>' . $item[$i] . '</td>';
        // If the next $i is divisible by 4, we have to close the row
        if ($i % 4 == 3)
            echo '</tr>';         
    }
    // If we didn't end on a row close, make sure to close the row
    if ($i % 4 != 3)
        echo '</tr>';
    ?>
</table>
like image 26
Peter Ajtai Avatar answered Feb 16 '23 00:02

Peter Ajtai