dimanche 5 mai 2019

PHP (un)check a checkbox from 2 dynamic arrays while comparing them

I have 2 arrays, $item and $previousItem. $item contains all possible selections $previousItem contains selections already stored in the database. For example I have check boxes with apple, orange, banana and in my database I recorded that the user previously selected apple and banana. How can I fill the check boxes so that only orange will be unchecked while the other two will be checked. The nested for loop creates duplicates if I have more than one value for $previousItem. This must be done using only php. Is there a sort function I can use for this?

Here's the code:

    for($i = 0; $i < $index; $i++)
        for($j = 0; $j < $count; $j++)
    {
        echo '<li>
                <!--these are the individual check boxes-->';
        echo '<input type="checkbox" name="item[]" id="$item+$count" value="' . $item[$j] . '"'.($previousItem[$i] == $item[$j] ?'checked': '') .'>
                <!--these are the values of the check boxes-->
                <label for="$item+$count">' . $item[$j] . '</label>
                <input type="hidden" name="item_list[]" value="' . $item[$j] . '">';
    }




Aucun commentaire:

Enregistrer un commentaire