Since I'm basically a designer and not a developer, I've bumped into a (probably pretty simple) problem that I can not seem to figure out.
My problem:
I want to add the value of the selected checkboxes together and display the sum of them as $sum
. Pretty straightforward I thought, but I seem to (1) need some form of initial check if any checkboxes are posted to avoid Warning: Invalid argument supplied for foreach()
, as well as (2) some kind of prevention from posting without selecting any checkbox at all.
I've been trying to resolve my issue by looking at related threads such as Invalid argument supplied for foreach(), and I've tried to use the solutions mentioned there, but unfortunately without success – you can see the lines I've commented out, if (is_array($product)) {
.
Goal
My end goal with this code is to create a form with let's say 3 segments/categories of checkboxes where the user must check at least one in each segment
(they could check all if they'd like, in my sample code only the first segment/category is supplied). Each checked box will provide a value that goes towards adding them all in a sum.
I'm happy to see any alternative solutions and optimizations, as long as you can explain or point me to an example of your improvements, since I'm very much a beginner with PHP.
Index.php
/* if (is_array($product)) { */
foreach ($_POST['product'] as $name => $value) {
$sum = array_sum(array_map('intval', $_POST['product']));
echo('sum: '.$sum);
}
/* } */
?>
<form action="index.php" method="post">
<label><input type="checkbox" name="product[1]" value="100" />100<br></label>
<label><input type="checkbox" name="product[2]" value="200" />200<br></label>
<label><input type="checkbox" name="product[3]" value="300" />300<br></label>
<br>
<input type="submit" name="submit">
</form>
<a href="index.php">reload</a>