Skip to content
PHP Logo

What is the best practice for concatenating checkbox values in PHP?

When dealing with multiple checkbox inputs in PHP, the best practice for concatenating their values is to loop through each checkbox input and check if it is checked. If checked, add its value to an array or string variable. This ensures that only the values of the checked checkboxes are concatenated together.

php
// Loop through each checkbox input
$concatenatedValues = '';
foreach($_POST['checkbox'] as $value) {
    // Check if checkbox is checked
    if(isset($value)) {
        $concatenatedValues .= $value . ', ';
    }
}

// Remove the last comma and space
$concatenatedValues = rtrim($concatenatedValues, ', ');

// Output concatenated values
echo $concatenatedValues;