Reputation: 1240
How to set a = 0
value for each checkbox
unchecked
Error:
Warning: array_combine() [function.array-combine]: Both parameters should have an equal number of elements in
PHP:
$combined = array_combine($_POST['name'], $_POST['day']);
foreach($combined as $name => $value) {
echo $name.' => '.$value;
}
HTML:
<form method="post" action="result.php">
<p>
<input type="text" name="name[]" value="seth" />
<input type="checkbox" name="day[]" value="7" />
</p>
<p>
<input type="text" name="name[]" value="jack" />
<input type="checkbox" name="day[]" value="4" />
</p>
<p>
<input type="text" name="name[]" value="david" />
<input type="checkbox" name="day[]" value="3" />
</p>
</form>
PS:
I won't use:
<select name="day[]" size="1">
<option value="0"> Non </option>
<option value="1"> Yes </option>
</select>
Upvotes: 0
Views: 1030
Reputation: 4530
Here you go. Hope this works for you. It's a bit more work then what you were hoping for probably.
result.php
<?PHP
$days = array();
$namecount = count($_POST['name']);
for($i = 0; $i < $namecount; $i++){
$days[$i] = isset($_POST['day'][$i]) ? $_POST['day'][$i] : 0;
}
$arr = array_combine($_POST['name'], $days);
print_r($arr);
?>
form.html
<form method="post" action="result.php">
<p>
<input type="text" name="name[]" value="seth" />
<input type="checkbox" name="day[0]" value="7" />
</p>
<p>
<input type="text" name="name[]" value="jack" />
<input type="checkbox" name="day[1]" value="4" />
</p>
<p>
<input type="text" name="name[]" value="david" />
<input type="checkbox" name="day[2]" value="3" />
</p>
<input type='submit' value='Submit' />
</form>
Upvotes: 1
Reputation: 174997
I can think of only 3 ways:
<input type=radio>
s with the same name, this will give you extra control over the content that is sent through. (Given in a previous answer)<input type=hidden>
, which has the same name as your checkbox, if the checkbox is not selected, the hidden input's value will be sent. (Given in a previous answer)Upvotes: 0
Reputation: 14808
Your problem is that unchecked checkboxes aren't even sent to the server, so as it is your 2 $_POST
arrays won't line up unless they are all checked. You should consider using radios and setting the value of the key in name
attribute.
ie do this for each input:
<form>
<p>
<input type="text" name="name[3]" value="david" />
<input type="radio" name="day[3]" value="yes" /> <label>Yes</label>
<input type="radio" name="day[3]" value="no" /><label>No</label>
</p>
</form>
Then do print_r($_POST)
and you will see your arrays line up. Another way is to do a hidden input (with exactly the same name=""
and it will act as a default value.
Upvotes: 2