Create Columns From Array

Create Columns From Array

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.

/*** the number of columns wide ***/
$num_cols 3;
/*** and array to traverse ***/
$animals = array(
'steve irwin',

/*** 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>';

The above snippet will produce a table like this:

wombatkangaroosteve irwin