PHPRO.ORG

Here is a simple example of taking an array and displaying it n colomns wide. This type of output is useful when you need to spread your results into 2, 3 or more columns. The work is done with the modulo operator (%). This operator checks for a remainder after division and so, can also be used to check if this is no remainder. In this way, the check for zero tells whether to begin a new table row when traversing the array.

Of course, this does not only apply to arrays, but can also be used when outputting database result sets that need to be in mulitple columns.


<?php
    
/*** the number of columns wide ***/
        
$num_cols 3;
    
/*** and array to traverse ***/
        
$animals = array(
        
'platypus',
        
'wallaby',
        
'dingo',
        
'wombat',
        
'kangaroo',
        
'steve irwin',
        
'emu',
        
'kookaburra',
        
'crocodile');
?>

<table>
<tr
style="background:orange;"><td>Only</td><td>This</td><td>Wide</td></tr>
<?php
    
/*** set a counter ***/
        
$i 0;
    
/*** loop over the array ***/
        
foreach ( $animals as $item )
        {
                
/*** use modulo to check if the row should end ***/
                
echo $i++%$num_cols=='</tr><tr>' '';
                
/*** output the array item ***/
                
echo '<td>'.$item.'</td>';
        }
?>
</tr>
</table>

The above snippet will produce a table like this:

OnlyThisWide
platypuswallabydingo
wombatkangaroosteve irwin
emukookaburracrocodile