Search code examples
phparrayscodeigniter

Checkboxing all values that are present in the array


Currently I am fetching all the values from my database and placing a checkbox next to them. By default all checkboxes are unchecked, but the checkboxes whose id is present in the database should be marked as checked. To do this I have used the following code:

View Class:

    <?php if($facilities) foreach($facilities as $facility):  ?>
     <?php foreach($checked_facility as $key => $value){ ?>
        <fieldset id="availablenetworked">
            <input type="checkbox" <?php echo ($value['facilities_id'] == $facility['id'] ? 'checked' : ''); ?> 
            name="facility[]" id="<?php echo $facility['id'] ?>" value="<?php echo $facility['id'] ?>"> 
            <label for="<?php echo $facility['id'] ?>"><?php echo $facility['title'] ?></label>
        </fieldset>
    <?php } endforeach; ?>

Doing this correctly checkmarks all the values that I have in my database, but messes up my view and makes it look like this:

enter image description here

$facilities is used to fetch all records of facilities and $checked_facility is used to check the values that a specific person has chosen.

The response returned from $checked_facility looks like this where I'm trying to access the facilities_id and marking all those with a checkmark in my list.

enter image description here


Solution

  • You have 2 nested loops, which is likely causing the duplication problems. Why not just pre-process your checked ids first and store them in an array. Then you can reference them in a single loop. Something like

    <?php 
    $checked = array();
    foreach($checked_facility as $key => $value){ 
      $checked[]=$value['facilities_id'];
    }?>
    

    Then, you can loop through your list and just check with in_array() https://www.php.net/manual/en/function.in-array.php

    <?php if($facilities) foreach($facilities as $facility):  ?>
            <fieldset id="availablenetworked">
                <input type="checkbox" <?php echo in_array($facility['id'], $checked) ? 'checked' : ''; ?> 
                name="facility[]" id="<?php echo $facility['id'] ?>" value="<?php echo $facility['id'] ?>"> 
                <label for="<?php echo $facility['id'] ?>"><?php echo $facility['title'] ?></label>
            </fieldset>
        <?php endforeach; ?>