Get total [checkbox] value
HTML:
<input type="checkbox" name="product[book]" value=开发者_如何学JAVA"10" /> book
<input type="checkbox" name="product[plane]" value="20" /> plane
PHP:
foreach ($_POST['product'] as $name => $value) {
echo $value;
}
How to get the total (sum) value
if the user select two fields (book & plane)
You can use array_sum:
$sum = array_sum(array_map('intval', $_POST['product']));
Assuming you already checked validity of the $_POST['product']
field.
In your form you have an array of product. If you foreach that, create a $total = 0; at the start, add the value to it, at the end you have a total.
You can check that would work by print_r($_POST)
and you'll see any selected values show as part of an array within the array of $_POST.
try
$total=0;
foreach ($_POST['product'] as $k) {
$total +=$k;
}
echo $total;
$pTotal = 0;
foreach ($_POST['product'] as $pVal)
{
$pTotal += intval($pVal,10);
}
Make sure you're explicit about the format type. Without checking, I would expect the values coming in to be strings, not integers... which will give you all sorts of headaches if you're trying to add them up. : )
精彩评论