So I wanted to display a 4 column table as part of a site. The issue was that I didnt know how many items I was going to have to display. It may be 1, it may be 3, it may be 4 or 5 or even 24.

I don like to repeat code unless I absolutely have to. So I wrote something similar to this to get around having to write the same code over and over again.

/* Display a dynamic 4 column table. (i.e. unknown number of results to show. */
$a = 0; //Control Variable.
while($row = mysql_fetch_array($results)) {						
	// First up we open the row if $a == 0
	if($a == 0) {
		echo "<tr>";
	} //if control == 0
	
	//Display the information in the column every time
	echo "<td>";
		echo "Column Information";
	echo "</td>";
		
	//If it is the end of a row, close off the row and reset the counter, or just add 1 to the control
	if($a == 3) {
		echo "</tr>";
		$a = 0;
	} else {
		$a++;
	}//if control == 0	
} //while getting results

//If we finish mid row we need to finish the row.
if($a <= 3) {
	/* We need to run through it enough times (up to 3)*/
	for($a = $a; $a <= 3; $a++) {
		//Add another blank column
		echo "<td>&nbsp;</td>";
		
		//If it is the last one close off the row.
		if($a == 3) {
			echo "</tr>";
		} //if control == 0	
	} //for 
} //if under 4 finish table