Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Currently, I have a column in database called answer to store all the answers for the form submitted. For now, the form itself have a "save" button whereby user can save the form if they're not free to finish it at the point of time. When the form is being saved, all the answers will be inserted into database.

Now my question is, my checkbox input answers are being inserted as example "1,2,3" if the question itself have option of "1,2,3,4,5". so I used a foreach loop to separate the data out and use if/else statement to check if it's same, marked as tick. But the question format end up to be like

x 1
  2
x 2
  3
  3
x 3
  4
  4
  4
  5
  5
  5

The output that I want is:

x 1
x 2
x 3
  4
  5 

The code for the printing of checkbox is like this:

First foreach is the options of the question, example "1,2,3,4,5".

Second foreach is the answers that the user selected after saving the form, example "1,2,3".

foreach ($arr as $row => $name) {
                        $arr = $name;    
if ($input == 'Multiple choice (multiple answers) [Check box]') {
                                 foreach ($arrAns as $values) {
                            if ($arr == $values) {  ?>
                                <input type="checkbox" name="<?php echo 'qns' . $qID; ?>[]" value="<?php echo $arr; ?>" class="required" checked/> <?php echo $arr; ?><br/>
                            <?php break; } else { ?>
                                <input type="checkbox" name="<?php echo 'qns' . $qID; ?>[]" value="<?php echo $arr; ?>" class="required"/> <?php echo $arr; ?><br/>
                                <?php
                            } } } } ?>

Is it possible to get the output that I want? Thanks for the help!

share|improve this question
1  
first, get your foreaches straight. I really believe that your checkboxes should be done on your outer foreach, and only the checked attribute should be handled in the inner foreach ( besides use if (in_array('foo', $array)) for that inner one ). And I really dislike $input == 'Multiple choice (multiple answers) [Check box]' as an if statement. Please split displayed text and logic content for your own safety. –  Najzero Jun 14 at 8:15
 
Also, what is $input and why are you checking it inside your foreach (i.e., at the start of every iteration of the loop) if its value is never changed during the course of the loop? –  daiscog Jun 14 at 9:24
 
$input is just for me to print out the question according to what the user selected for the input like radio buttons, checkbox and etc. –  user2376259 Jun 14 at 9:52
add comment

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.