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
}
?>
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Sudeep
  • 513
  • 3
  • 5
  • 9
  • 1
    http://stackoverflow.com/questions/2268887/php-checkbox-input http://stackoverflow.com/questions/6291370/how-to-get-value-of-checked-checkbox-in-php – useraged Aug 16 '11 at 12:55
  • Checkboxes are always `TRUE` or `FALSE`, that's the point of them - what value do you want, exactly? – DaveRandom Aug 16 '11 at 12:55
  • 2
    @DaveRandom: That's not true. They either have their assigned value, or they are not set. – Lightness Races in Orbit Aug 16 '11 at 12:55
  • @DaveRandom only partially true. The checkbox also contains a value, which is only sent if the checkbox is ticked – calumbrodie Aug 16 '11 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... :-) – DaveRandom Aug 16 '11 at 13:00

1 Answers1

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
}
J0HN
  • 26,063
  • 5
  • 54
  • 85
  • 3
    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. ``) – feeela Aug 16 '11 at 13:06
  • Right, FF also sends 'on'. My mistake :) Edited – J0HN Aug 16 '11 at 13:10
  • You really shouldn't rely on the string, that is sent, if no value was given. Better to just check, which names are sent. – feeela Aug 16 '11 at 13:12
  • I'm using the second approach. Always :) But checking the names makes sence too. – J0HN Aug 16 '11 at 13:15
  • Often I just need a checkbox like 'terms-of-service-accepted', where using the name is the easiest way… – feeela Aug 16 '11 at 13:22
  • Sure, but that's not the case for this question. – J0HN Aug 16 '11 at 13:27