Php if iterator is divisible by operator for dynamic columns

I am trying to create a dynamic column list that will consist of 4 columns (PHP). Im echoing from the array, and every time the 4 elements of the array are echod, I would like to wrap these 4 elements of the array in a div called "column".

Basically, I thought that I could do this with my own calculation of the $ i ++ operator, but firstly, I had problems starting an account from nothing but zero (I tried to set the variable initially outside of each cycle).

Anyway, if you could kindly show me how to check if $ ++ is divisible by 4 in php so that I can insert if if $ i ++ is divisible by 4, then echo "", this will be very grateful. But first, I believe that I need to figure out how to start counting in 1 (so that if $ i ++ work divided by 4 will work ... right?)

+4
source share
3 answers

If you divide by 4, it will be integer division, and the coefficient will be a factor of 4. What you probably want is the % module operator . This will give you the rest. Therefore, when $i is a multiple of 4, it will be 0.

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

The module may be inefficient. Since you are dividing into several of the two, you can shift the bits by 2. This is the same as dividing by 4 and much more efficient. Check bit offset .

+11
source

% - module operator. It returns the remainder after division, so 7 % 4 == 3 .

You really need to start at 0. This is because 0 % 4 == 0 and 4 % 4 == 0 ... And you want the first element to be a new line! So you want newlines at 0, 4, 8, etc. If you start with one, then 1, 2, and 3 will not be on the line.

In addition, we must remember to close the line for each item to a new line.

Finally, if we exit our loop without closing the last line, we must do so after exiting the loop.

I will show how to do this with tables, but you can use divs with classes just as easily.

 <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> 
+5
source

Modulus!

$a % $b The remainder of $ a divided by $ b.

http://php.net/manual/en/language.operators.arithmetic.php

0
source

Source: https://habr.com/ru/post/1315476/


All Articles