tags:

views:

1042

answers:

6

I wanted to echo an image every after 3 post via XML here is my code :

<?php
// URL of the XML feed.
$feed = 'test.xml';
// How many items do we want to display?
//$display = 3;
// Check our XML file exists
if(!file_exists($feed)) {
  die('The XML file could not be found!');
}
// First, open the XML file.
$xml = simplexml_load_file($feed);
// Set the counter for counting how many items we've displayed.
$counter = 0;
// Start the loop to display each item.
foreach($xml->post as $post) {
  echo ' 
  <div style="float:left; width: 180px; margin-top:20px; margin-bottom:10px;">
 image file</a> <div class="design-sample-txt">'. $post->author.'</div></div>
';

  // Increase the counter by one.
  $counter++;
  // Check to display all the items we want to.
  if($counter >= 3) {
    echo 'image file';
    }
  //if($counter == $display) {
    // Yes. End the loop.
   // break;
  //}
  // No. Continue.
}
?>

here is a sample first 3 are correct but now it doesn't loop idgc.ca/web-design-samples-testing.php

+2  A: 

use modulo to check if the counter is a multiple of 3.

E.g.

// this isn't php but you should be able to get it
int x =3;

for(int i=0; i<10; i++)
{
    if(i%x == 0)
    {
        // display image
    }
}

http://en.wikipedia.org/wiki/Modulo http://uk3.php.net/manual/en/language.operators.arithmetic.php

Greg B
+1  A: 

basically checks if counter is divisable by 3. hence every 3 posts :)

<?php

$feed = 'test.xml';

if(!file_exists($feed)) {
  die('The XML file could not be found!');
}

$xml = simplexml_load_file($feed);

$counter = 0;

foreach($xml->post as $post) {
  echo ' 
  <div style="float:left; width: 180px; margin-top:20px; margin-bottom:10px;">
 image file</a> <div class="design-sample-txt">'. $post->author.'</div></div>
';


  $counter++;

  if($counter % 3 == 0) {
    echo 'image file';
    }

}
?>
Ozzy
so i get the answer then he removes it >.<
Ozzy
Your solution *is* correct, but the ones using modulus are better.
Anax
mine DOES use modulus T_T
Ozzy
+7  A: 

The easiest way is to use the modulus division operator.

if ($counter % 3 == 0) {
   echo 'image file';
}

How this works: Modulus division returns the remainder. The remainder is always equal to 0 when you are at an even multiple.

There is one catch: 0 % 3 is equal to 0. This could result in unexpected results if your counter starts at 0.

R. Bemrose
Thanks it worked!
kwek-kwek
another problem is that my lightbox doesn't worked anymore.... is there any xml php conflicts?
kwek-kwek
A: 

How about: if(($counter % $display) == 0)

Ivarska
A: 

every 3 posts?

if($counter % 3 == 0){
    echo IMAGE;
}
mateusza
A: 

I am using this a status update to show a "+" character every 1000 iterations, and it seems to be working good.

if ($ucounter % 1000 == 0) { echo '+'; }
meme