I am getting all the data from the database and one of my column data is 1|3|6|8
.
I am using explode to get the output.
Now, I have a checkbox list that I am getting from the database and I have to pass the explode value in the checkbox list to check the checkbox.
JavaScript
x
<?php
$exp=explode('|', $Info['recog']); //getting from the database
print_r($exp) // output is Array ( [0] => 120 [1] => 121 [2] => 130 [3] => 156 )
foreach ($exp as $key => $e) {
print_r($e);
}
// displaying the list
foreach ($checkLists as $key => $check) {
?>
<li>
<label class="regBox">
<div class="mb-3"><img src="<?php echo $check['img'];?>" alt=""></div>
<input type="checkbox" name="recog[]" value="<?php echo $check['cid'];?>">
<p><?php echo $check['title'];?></p>
<div class="checkmark"></div>
</label>
</li>
<?php }?>
I know I have to use something like foreach
and the <?php echo ($check['cid']==$e['value'] ? 'checked' : '');?>
Advertisement
Answer
Ok – I think that because the exploded string yields a simple array the inner foreach
loop needs only to check if the current array member is equal to the cid
field for the current record..
JavaScript
<?php
$exp=explode( '|', $Info['recog'] );
foreach( $checkLists as $key => $check ) {
$checked='';
foreach($exp as $i){// simple integer
if( (int)$i == (int)$check['cid'] ){
$checked='checked';
break;
}
}
# Alternative
# $checked=in_array($check['cid'],$exp) ? 'checked' : '';
?>
<li>
<label class="regBox">
<div class="mb-3">
<img src="<?php echo $check['img'];?>" alt="" />
</div>
<input type="checkbox" name="recog[]" value="<?php echo $check['cid'];?>" <?php echo $checked;?>/>
<p><?php echo $check['title'];?></p>
<div class="checkmark"></div>
</label>
</li>
<?php
}//close outer foreach
?>