Suffii
Suffii

Reputation: 5784

How To Pass Values of Associated Array to Check-boxes

Following snippet is generating 3 checkboxes with correct state from comparing two arrays but the outpt dosent render any value for lables like

enter image description here

but I need to display the value of $items for the inputs like

enter image description here

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

Answers (2)

Amr Berag
Amr Berag

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

Amit Merchant
Amit Merchant

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

Related Questions