Displaying and editing checkboxes

A function to generate checkboxes for selecting options from a provided array. While adding a new entry to the database, the result will be a string with array's options separated by a comma, e.g., "1,5,9" or "high,low,middle" therefore, you need to set a DB column to be VARCHAR or anything of that type.

The Function

The function serves three purposes:

  1. Display checkboxes while adding a new entry to the database.
  2. Display checkboxes with pre-selected options while editing entries.
  3. Print out regular content (string) on the website while presenting data grabbed from the database.

<?php
/**
 * Print out checkboxes for selecting options.
 *
 * This function generates checkboxes for selecting options from a provided array.
 * It also checks the checkboxes if the option IDs are present in the $dbEntry string.
 *
 * @param string $name The name attribute for the checkboxes.
 * @param array $checkboxArray An associative array of option IDs and names.
 * @param bool $printCheckbxs (Optional) Indicates whether to print checkboxes or just output names.
 * @param string $dbEntry (Optional) A comma-separated string of option IDs stored in the database.
 *               If provided, checkboxes for corresponding option IDs will be checked.
 */
function printCheckboxes($name, $checkboxArray, $printCheckbxs = true, $dbEntry = '')
{
    // If $dbEntry is not empty, parse it into an array of option IDs
    $array_ids = !empty($dbEntry) ? explode(',', $dbEntry) : [];

    // Get the keys of the checkbox array
    $checkboxKeys = array_keys($checkboxArray);

    // Initialize an array to store option names (if $printCheckbxs = false)
    if (!$printCheckbxs) {
        $justNames = [];
    }

    // Iterate over each option in the checkbox array
    foreach ($checkboxArray as $output_id => $output_name) {

        // Check if the option ID is in the $array_ids array
        $checked = in_array($output_id, $array_ids) ? 'checked' : '';

        if ($printCheckbxs) {
            // Create a checkbox for the option
            echo '<label><input type="checkbox" name="' . $name . '[]" value="' . $output_id . '" ' . $checked . '> ' . $output_name . '</label>';
        } else {
            // Store the option name for later use
            $justNames[] = $checked ? $output_name : '';
        }
    }

    // If not printing checkboxes, output the names separated by commas
    if (!$printCheckbxs) {
        // Filter out empty names and concatenate them with commas
        $names = array_filter($justNames);
        echo implode(', ', $names);
    }
}

Usage

Adding a new entry:


<?php
// Function call to generate checkboxes
printCheckboxes('features', $featuresArr, true);

Editing an existing entry:


<?php
// Generating checkboxes with pre-selected options based on the $row['features'] array retrieved from the SQL query.
printCheckboxes('features', $featuresArr, true, $row['features']);

Printing results from the database:


<?php
// Print regular content (string) based on database data
printCheckboxes('features', $featuresArr, false, $row['features']);

Scroll to Top
Wordpress I've lately been using:
  • Wordpress
  • PHP
  • CSS
  • jQuery

Summary: Font-end and Back-end developer, also designer with 25+ years of experience. Currently based in Poland. Eligible to work in the US (US Social Security Number holder) for any employer on W2 / 1099 basis. Utilizes both technical skills and designing aptitude. Lived and worked in Europe, Australia and North America.

PHP CMS HTML5 CSS3 RWD OOP MySQL PDO JS jQuery JSON GIT Bitbucket GitHub Gulp