Allow invalid foreach () argument when adding sum of checkboxes

Since I am primarily a designer and not a developer, I ran into a (perhaps quite simple) problem that I cannot understand.

My problem:

I want to add the value of the selected checkboxes together and display their sum as $sum

. Pretty simple I thought, but it seems to me that (1) some form of initial validation is needed if any checkboxes are posted to avoid Warning: Invalid argument supplied for foreach()

, and (2) a kind of prevention from posting without any checkbox.

I tried to solve my problem by looking at related streams such as Invalid argument for foreach () and I tried the solutions mentioned there but unfortunately with no success - you can see the lines I commented out if (is_array($product)) {

.

purpose

My end goal with this code is to create a form with three checkbox segments / categories where the user has to check at least one in each segment

(they could check everything if they want, only in my example code the first segment / category is provided). Each checkbox will contain a value that will be added to the amount.

I am happy to see any alternative solutions and optimizations if you can explain or point me to an example of your improvements as I am very new to 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>

      

+3


source to share


2 answers


this should work :)

if (isset($_POST['product'])) {
    $product = $_POST['product'] ;
     if (is_array($product)) {
        foreach ($product as $name => $value) {
            $sum = array_sum(array_map('intval', $_POST['product']));

            echo('sum: ' . $sum);
        }
    }
}

      

Or slightly optimized :)

$product = $_POST['product'];
if(is_array($product)) {
    $sum = array_sum(array_map('intval', $product));
    echo('sum: ' . $sum);
}

      



The error occurs because it is $_POST['product']

not a valid array on first run

EDIT

You is_array

will work, but I don't think you declared $ product before using it, if you did, I think your code would work :)

+1


source


$sum = $_POST[form_value_1]+$_POST[form_value_2];

      



Etc.

-2


source







All Articles