PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 1, 2022

[FIXED] Checkboxing all values that are present in the array

 March 01, 2022     arrays, codeigniter, php     No comments   

Issue

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; ?>


Answered By - Kinglish
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing