I have multiple checkbox values stored in a single column in my DB ( Example cat,dogs or dogs,cows etc. it is retrieved as $animals and exploded to compare the values.
$animal_values = explode(",", $animals);
$cat = "cat";
$dogs = "dogs";
$cow = "cow";
foreach($animal_values as $value) {
if( $value == $cat ){
echo '<li>
<input type="checkbox" id="cat" checked="checked" name="animals[]" value="cat" />
<label for="cat">Cat</label>
</li>';
}
if( $value == $dogs ){
echo '<li>
<input type="checkbox" id="dogs" checked="checked" name="animals[]" value="dogs" />
<label for="dogs">dogs</label>
</li>';
}
if( $value == $cow ){
echo '<li>
<input type="checkbox" id="cow" checked="checked" name="animals[]" value="cow" />
<label for="cow">cow</label>
</li>';
}
This way the values that are present shows up as checked checked boxes.
But the thing is I also want to show boxes for whose values are missing as unchecked boxes. How can I achieve this ??
<?php
$animal_value = explode(",", $animal);
echo '<li>
<input type="checkbox" id="cat"';?> <?php if (in_array("cat", $animal_value)) { echo 'checked="checked"'; } ?> <?php echo 'name="animal[]" value="cat" />
<label for="cat">Cat</label>
</li>';
echo '<li>
<input type="checkbox" id="dog"';?><?php if (in_array("dog", $animal_value)) { echo 'checked="checked"'; } ?> <?php echo ' name="animal[]" value="dog" />
<label for="dog">Dog</label>
</li>';
echo '<li>
<input type="checkbox" id="cow"';?><?php if (in_array("cow", $animal_value)) { echo 'checked="checked"'; } ?> <?php echo 'name="animal[]" value="cow" />
<label for="cow">COW</label>
</li>';
?>
Any suggestions for Improvement or any other approach its welcome.