1

I have one form which contain product information and one field which have two(2) check box for status(want to post advertise for that particular product or not.)and i have one field which is for "add more" it will clone whole div and also check boxes so i have more then one output but I don't have getting single value.

<div>
     <label>I want to Advertise This Item</label>
     <input type="checkbox" value="1" name="chkyes[]" id="chkyes[]"/>
     Yes
     <input type="checkbox" value="0" name="chkyes[]" id="chkyes[]"/>
     No 
</div>

Above code is for selecting checkbox, and below code which echo value in array but I don't get the value of checkbox.

if(count($_POST)){
    $len = count($_POST['producttitle']);
    for ($i=1; $i < $len; $i++){
        echo $_POST['chkyes'][$i];
    }
}
Bas van Dijk
  • 9,933
  • 10
  • 55
  • 91

5 Answers5

2

why you dont use foreach?

for eg

if (isset($_POST['chkyes'])) {
    foreach ($_POST['chkyes'] as $value) {
        echo $value;
    }
}
MaiKaY
  • 4,422
  • 20
  • 28
2

The first approach:

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

This way you could access them in PHP with

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

The second approach:Set value's attributes on checkboxes:

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

With this you'll receive only checked values:

foreach ($_POST['chkyes'] as $id){
    //process your id
 }
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

Array of input start from an index of 0, and use $_POST['chkyes'] instead of $_POST['producttitle']

 if(count($_POST)){
     $len = count($_POST['chkyes']);
     for ($i=0; $i < $len; $i++){
         echo $_POST['chkyes'][$i];
     }
 }

also you can't give id's like chkyes[] give it as chkyes1, chkyes2

Deepika Janiyani
  • 1,487
  • 9
  • 17
1

Try Below code

<?php
if($_POST['submit'] == 'submit'){
    $len = count($_POST['chkyes']);
    for ($i=0; $i < $len; $i++){
        echo $_POST['chkyes'][$i];
    }
}
?>


<form name="test" method="POST">
<div>
     <label>I want to Advertise This Item</label>
     <input type="checkbox" value="1" name="chkyes[]" id="chkyes[]"/>
     Yes
     <input type="checkbox" value="0" name="chkyes[]" id="chkyes[]"/>
     No 
</div>
<input type="submit" name="submit" value="submit">
</form>
w3b
  • 823
  • 6
  • 14
1

Only checkboxes that are checked are submitted in the form. They'll be collected in an array $_POST['chkyes'], but the indexes won't be the same as corresponding text inputs. You need to process them with their own foreach loop, not the same loop as for other inputs.

For what you're doing, why aren't you using radio buttons or a single checkbox? What if the user checks both Yes and No?

Barmar
  • 741,623
  • 53
  • 500
  • 612