samedi 3 septembre 2016

PHP set the checkbox to be checked if data in Array 1 equal Array 2

I have array that's retrieved from mysql.

Array item_category is an Array that shows all the categories.

Array selected_category is an array that shows the selected categories.

$item_category[32]="western food";  
$item_category[33]="chinese food";  
$item_category[34]="mix food";     
$item_category[35]="japanese food"; 
$item_category[36]="korean food";   
$item_category[37]="italian food";  

$selected_category[32]="western food"; 
$selected_category[33]="chinese food";  
$selected_category[34]="mix food";    

foreach ($item_category as $key => $value) {

    echo '<input type="checkbox" name="check_list[] "value="'.$key.'"> '.$value.'<br>';

}

enter image description here

  1. use foreach loop to display out all the categories

  2. check the checkbox in Array $selected_category.

So my question is how to check the checkbox just like the screenshot since they have the same "Key" in these 2 Arrays? I try something with the following but it doesn't work as what I expected.

$checked = true ? "checked" : "";
echo '<input type="checkbox" ' . $checked . ' name="check_list[] "value="'.$key.'"> '.$value.'<br>';




Aucun commentaire:

Enregistrer un commentaire