View Single Post
Old 05-07-2004, 05:36 PM   #3 (permalink)
sde
Moderator
 
sde's Avatar
 
Join Date: May 2002
Location: us.ca
Posts: 4,505
sde is on a distinguished road
ok .. first of all you need to get the total rows so you can determine what row is the final row. then set a row counter variable to count rows
PHP Code:
// assign the total full rows
$total_rows floor($count/3);

// add 1 to total rows if there is one more incomplete row
if($count%3>0){$total_rows++;};

// set row counter to 0
$row_number 0
at the beginning of each row, increment the row counter:
PHP Code:
$row_number++; 
then, when you print each cell .. test to see if it is the last row, and print the align tag if true. you can shorten up the code by using the ternary operator as i have here:
PHP Code:
echo "<td width=125" . (($row_number==$total_rows)?" align=center":"") . ">$each</td>\n"
here is a full working script with this implemented:
PHP Code:
<?
$array 
= array("a","b","c","d","e","f","g","h","i","j","k");
$count count($array);

// assign the total full rows
$total_rows floor($count/3);

// add 1 to total rows if there is one more incomplete row
if($count%3>0){$total_rows++;};

// set row counter to 0
$row_number 0;

echo 
"<table border=1>";



foreach(
$array as $each)
{
    
// make a new if the remainder of $i divided by 3 == 0
    
if($i == 0)
    {
        
// increment the row number variable
        
$row_number++;
        echo 
"<tr>";
    }
          
    
// use the ternary operator to inject align tag if on the last row
    
echo "<td width=125" . (($row_number==$total_rows)?" align=center":"") . ">$each</td>\n";
          
    
// add an extra <td></td> if there are not enough columns to complete the table
    // only test if $i is on the last item of the array
    
if($i == ($count 1))
    {
      
// keep adding blank cells till it's at the end
        
while(($i 1) % != 0)
        {
           echo 
"<td>&nbsp;</td>\n";
           
$i++;
        }                
    }            
          
    
// end table row if the remainder of $i+1 divided by 3 is 0
    
if(($i 1) % == 0)
    {                
      echo 
"</tr>";
    }
      
    
$i++;
}

echo 
"</table>";
?>
sleep well
__________________
Mike
sde is offline   Reply With Quote