I need to write a PHP function, but in fact I have a math question.
I have a variable number of results. I want to print my results in alternating rows of 3 and 4 columns. To do so, I have to know for each result, in what type of row it is located (aka, how many columns it's row has).
Ik know I can do it in PHP using 2 variables, but I assume there if a mathematical function to calculate for each item (which has an index starting at 0) in what type of row it is situated.
You can use this formula to determine on which kind of a row you are at.
$className = (($index % 7) < 3 ? 'row-with-three' : 'row-with-four')
Since the pattern repeats every 7 objects we start by wrapping the value around, $index % 7
. This will provide a value between 0
and 6
inclusively. Then we can check if it's one of the first three by doing < 3
, if it is then it's a row that has three objects. Otherwise it has four objects.
use count() to figure it out for you.
<?php
for( $i=0; $r=mysqli_fetch_assoc( $query ); $i++ ){
if( count( $r ) == 4 ){
echo "<tr><td></td><td></td><td></td><td></td></tr>";
}
if( count( $r) == 3 ){
echo "<tr><td></td><td></td><td colspan=\"2\"></td></tr>";
}
}
?>