Top Results Top Results - 10 days ago 6
PHP Question

Insert random blocks in a foreach loop

I have posts that I am displaying through a

foreach
loop. Within this I would like to throw in some advertising blocks.



I have posts and advertising blocks working with no issues. The posts are coming from an array and the advertising blocks I am manually inserted.

The hiccup I am seeing is how I am throwing in these ads into the
foreach
loop. I want it to add them but not interrupt the posts themselves and that is what I am experiencing.



I have 3 advertising blocks and 12 posts per page. When the page loads there should be a total of 15 blocks and instead I am getting 9. Those ads also not static - I have them coming in to be placed anywhere within those 15 blocks in total.


Here is quick run down of the script I am using (a readers digest version).



$i = 0;
foreach ($posts AS $post) {

$i++;

if ($adblock == $i) {
//insert advertisement block
}
else if ($adblock == $i) {
//insert advertisement block
}
else if ($adblock == $i) {
//insert advertisement block
}
else {
//insert post block
}

}

Answer

Without too much complexity, if the number of posts/adv per page is static, you can use a simple math to place your adv like this:

$i=0;
foreach($posts as $post){
  $i++; 

  if($i%3==0) { /* insert additional adv block */ }

  /* insert post block at anytime*/
}

you can change the ($i%3==0) to any other number; with 3 you will get an adv every 3 posts. need more adv, make it ($i%2==0), need less, make it ($i%4==0), etc.