gosulove gosulove - 3 months ago 10
MySQL Question

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>';

Answer

You need to check if $key of $item_category presents in $selected_category. This can be done with isset function:

foreach ($item_category as $key => $value) {
    // check if `$key` set in `$selected_category` 
    $checked = isset($selected_category[$key])? 'checked' : '';

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