rudtek rudtek - 2 months ago 9
PHP Question

how to have differnt content every 3rd iteration of while statment in php

I'm trying to create a while statement that will give different results for the 4th and then every 3 after that for columns.

so its going to be iterations 1,4,7,10 etc

Here is what i have

$count = $query->post_count;
$i = 1;
$located="";

while ( $query->have_posts() ) : $query->the_post();

$located.= '<h2 class="gold"><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
$located.= $shopaddress.'</br>';
$located.= $opentime.' - '.$closetime.'</br>';
$located.= $shopphone.'</br>';
if ($i == '1' || $i == '4'){
$located.=".";
}else {
$located.=", ";
}
$i++;


endwhile;

I was thinking that this would work

if ($i - 1 % 3 == 0){
$located.=".";
}else {
$located.=", ";
}


but i'm it doesn't return results different results (presumably the math set wrong)

if ($i % 3 == 1)


this seems to work but i'm not sure why and if it's just a fluke. how does this work?

Answer

You were close...you just need to take into account order of operations and group your operators - it should be:

if (($i - 1) % 3 == 0) 

Your statement is executing the modulus first, so when $i = 4, you have (4 - (1 % 3)), which equals 3.

Comments