I have two arrays responds back from server:
I need to display list of check-boxes of all allergies and mark the ones that exist in the other array as checked.
The second array can be null
.
How can I loop through both arrays without multiplying the results by array1 * array2
.
This code results into 8 check-box inputs because the list of all allergies is 4 and the product has only 2 allergies so the loop is executed 8 times!
<?php
$checked ="";
if (isset($allergies)) { // array of all allergies
foreach ($allergies as $key => $value) {
if(isset ($productAllergies)) { // array of product allergies
foreach ($productAllergies as $productkey => $prodValue) {
// echo 'product allergy'. $prodValue['allergy_id'] .' general'.$key ;
if( $prodValue['allergy_id'] ==$key )
$checked ='checked';
else
$checked ='';
?>
<?php
} // foeach close
} // if close ?>
<input type="checkbox" name="allergy[]" value="<?php echo $key; ?>" <?php echo $checked; ?>/>
<label>
<?php echo $value; ?>
</label>
<?php } // foreach close
} // if close
?>
Can somebody help to clarify the logic I should follow to display the checkbox list with checked values.
If I understand the format properly this could work:
<?php
$checked ="";
if (isset($allergies)) { // array of all allergies
foreach ($allergies as $key => $value) {
if(isset ($productAllergies)){ // array of product allergies
$k2 = array_search($key, $productAllergies);
if (!empty($productAllergies[$k2])) {
$checked = 'checked';
}
}
}
}
?>