Search code examples
phpmysqlechohtml-tableimplode

New table column, for every echo'd checkbox (php, mysql)


I am using the script below to display checkboxes based on what is in my mySQL table by using explode/implode. It then echoes either a checked checkbox or an unchecked checkbox based on what the location field in my table contains (e.g., Vip area,Raised Area, Garden Area).

<?


$aColors = array("Upstairs Function Room", "Whole Raised Area", "VIP Area", "Piano Area", "DJ Table" , "Canopy area" , "Garden Area", "Whole Bar", "Back Bar Tables" , "Raised Area Table 1", "Raised Area Table 2", "Raised Area Table 3", "Raised Area Table 4", "Raised Area Table 5", "Raised Area Table 6");

//converting comma separated into array using explode function
$dbcolors= explode(',',$row['location']);

foreach ($aColors as $locations) {

    if(in_array($locations,$dbcolors)) {
        echo "<input name=\"locations[]\" type=\"checkbox\" value=\"$locations\" CHECKED> $locations <br> ";
    } else
    {
        echo "<input name=\"locations[]\" type=\"checkbox\" value=\"$locations\"> $locations <br>";
    }
}
?>

This works fine but I can only get it to echo a long list of checkboxes... What I would like is to display it in a table and say for every 5 checkboxes that are displayed a new column created (effectively I should end up with about 3 columns) but I am stumped at how I can achieve this... Any help is much appreciated.

Rob


Solution

  • The trivial way would be a counter $i that you initialize with $i = 0 outside the foreach and increment it with $i++ inside the foreach, then every time $i % 5 == 0 is true you start a new column (echo '</td><td>').

    If you have additional styling it might be easier to split the array with array_chunk() like this: foreach (array_chunk($aColors, 5) as $block) { } and access them with $block[0], $block[1] ... $block[4] inside the foreach.