1

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] . '">';
    }

1 Answer 1

1

You only want one checkbox for each element in $item. Therefore only do one loop, over $item. It is giving duplicates because it is listing the elements in $item (the $j loop) for every element in $previousItem (the $i loop).

Read up on PHP: in_array function. If you use that in place of $previousItem[$i] == $item[$j], you can eliminate the $previousItem loop. The syntax would be something like in_array($item[$j],$previousItem)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.