0

When I pass the html form having checkboxes to a php page, when I retrieve them I get value true for all the boxes that I have checked, and false for unchecked boxes. I need to get the value only.

<?php 
$contact=$_POST['contact'];

foreach ($contact as $conid){
   echo $conid
}
?>
5
  • 1
    stackoverflow.com/questions/2268887/php-checkbox-input stackoverflow.com/questions/6291370/… Commented Aug 16, 2011 at 12:55
  • Checkboxes are always TRUE or FALSE, that's the point of them - what value do you want, exactly? Commented Aug 16, 2011 at 12:55
  • 2
    @DaveRandom: That's not true. They either have their assigned value, or they are not set. Commented Aug 16, 2011 at 12:55
  • @DaveRandom only partially true. The checkbox also contains a value, which is only sent if the checkbox is ticked Commented Aug 16, 2011 at 12:56
  • 1
    @kissmyface OMG I cannot believe I have managed to never know that. I have just tried it and it's true, I have never bothered to try adding a value="" attribute to a checkbox before... I'll just shut up I think... :-) Commented Aug 16, 2011 at 13:00

1 Answer 1

4

One possible approach is to set names like that:

<input type='checkbox' name='box[1]'>
<input type='checkbox' name='box[2]'>
<input type='checkbox' name='box[3]'>

This way you could access them in PHP with

foreach ($_POST['box'] as $id=>$checked){
    if ($checked =='on')
        //process your id
}

The second approach is more clean, I think. Set value's attributes on checkboxes:

<input type='checkbox' name='box[]' value='1'>
<input type='checkbox' name='box[]' value='2'>
<input type='checkbox' name='box[]' value='3'>

With this you'll receive only checked values:

foreach ($_POST['box'] as $id){
        //process your id
}
Sign up to request clarification or add additional context in comments.

6 Comments

Your first approach isn't correct. $checked == 'true' will (always) return false, since for example Chromium sends 'on' if a checkbox was checked. If you set a value for a checkbox, that value will be sent. Using the values and your second approach, it's possible to not only sent IDs, but also associated values. (e.g. <input type='checkbox' name='box[1]' value='value-for-ID-1'>)
Right, FF also sends 'on'. My mistake :) Edited
You really shouldn't rely on the string, that is sent, if no value was given. Better to just check, which names are sent.
I'm using the second approach. Always :) But checking the names makes sence too.
Often I just need a checkbox like 'terms-of-service-accepted', where using the name is the easiest way…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.