rwhite
rwhite

Reputation: 430

increment a variable based on loop count

I have a PHP function where an undefined number of images in a directory are being output to the browser. The images are being read in to an object. The issue I'm having is how the images are presented. I want to put them in a table, four <td> cells in a row. Here is the code:

function displayThumbList(){

   $tlist = $this->getThumbList();
   $i = 0;
   $e = 3;
   echo '<table width="400px" border=1><tr>';
   foreach ($tlist as $value) {
    echo "<td width=\"90px\" height=\"50px\"><a href=\"showImage.php?id=".$this->getBaseName($value,$this->thumbPrefix)."\" target=\"imgHolder\"><img class=\"timg\" src=\"thumbnail/".$value."\" alt=\"a\" /></a></td>";
    $_GET['imagefocus'] = $this->getBaseName($value,$this->thumbPrefix);

  //here is where the condition for adding a <tr> tag is evaluated 
  if ($i == $e){
       echo '<tr>';
     }

  $i++; //increments by 1 with each foreach loop
 }
 echo '</table>';
}

The first time $i(third time through foreach loop) is equal to $e, the process adds the as expected. I need $e to increment by 3 AFTER each time the condition is met.

The number of images are undefined. If there are 21 images in the directory, $i would increment 21 times and $e should increment 7 times adding 3 with each increment (3,6,9,12,15 etc).

I guess I'm looking for an increment based on another loop condition (every time equality is reached). Any thoughts? rwhite35

Upvotes: 1

Views: 2427

Answers (2)

Shashank Mehta
Shashank Mehta

Reputation: 120

You want to update $e when $i == $e. That condition is already being used in your if statement. Just add

$e += 3;

and you are done.

if ($i == $e){
   echo '<tr>';
   $e += 3;
 }

Upvotes: 0

DGH
DGH

Reputation: 11549

if ($i == $e){
   echo '<tr>';
   $e = $e + 3;
 }

Alternatively, use modulo, something like

if ($i % 3 == 0)

Upvotes: 3

Related Questions