Reputation: 5784
Following snippet is generating 3 checkboxes with correct state from comparing two arrays but the outpt dosent render any value for lables like
but I need to display the value of $items
for the inputs like
can you please let me know how modify the code to achieve this?
<?php
$items = ['2' => 'Full', '4' => 'No', '3' => 'Semi'];
$selected = [2, 3];
$keys = array_keys($items);
foreach($keys as $key ){
if (in_array($key, $selected)) {
echo '<input id="checkBox" value="'.$key.'" type="checkbox" checked>';
}
else{
echo '<input id="checkBox" value="'.$key.'" type="checkbox">';
}
}
?>
Upvotes: 1
Views: 24
Reputation: 1118
Try it this way:
foreach($items as $key => $value ){
if (in_array($key, $selected)) {
echo '<input id="checkBox" value="'.$key.'" type="checkbox" checked>'.$value.'<br>';
}
else{
echo '<input id="checkBox" value="'.$key.'" type="checkbox">'.$value.'<br>';
}
}
Upvotes: 1
Reputation: 1043
Try this:
<?php
$items = ['2' => 'Full', '4' => 'No', '3' => 'Semi'];
$selected = [2, 3];
$keys = array_keys($items);
foreach($keys as $key){
if (in_array($key, $selected)) {
echo '<input id="checkBox" value="'.$key.'" type="checkbox" checked> '.$items[$key];
}
else{
echo '<input id="checkBox" value="'.$key.'" type="checkbox"> '.$items[$key];
}
}
?>
Upvotes: 1