views:

41

answers:

4

Hello! So I've created a form wich, by the post function, send me several values. $_POST[groups] sends me, using 4 different checkboxes values 1, 2, 4 and 8. $_POST[retailgroup] does the same, but only the values 1, 2 and 4. The problem is that I want these to add up together and then send the sum of the values to a MySQL table. I've managed to do one using the following foreach loop:

foreach ( $_POST as $val ) {
    foreach ( $val as $key=>$final_val ) {
        $group = $group+$final_val;
    }
}

The problem starts when I need to have these two apart from each other since they are going into separate columns in the table.

To be clear I've assigned different groups different values (always taking the prev value times two, just like counting binary) like 1, 2, 4 and 8. By adding them together I can determine membership in the groups by doing a subtraction "backwards". Since there are different kinds of groups I want them into two separate fields of the table.

I hope everything is clear.

Any idea on how to do this?

A: 

try

foreach ( $_POST[groups] as $key=>$final_val ) {
   //do stuff for first group
}
foreach ( $_POST[retailgroup] as $key=>$final_val ) {
   //do stuff for second group
}

and after you can make whatever you want with the variables got from loops

Centurion
+3  A: 

you want to use:

$groups_sum = array_sum($_POST['groups']);
$rgroups_sum = array_sum($_POST['retailgroups']);

This will be faster and clearer than a foreach loop in this case.

aaronasterling
You beat me to it by a few seconds.
Joseph
A: 
$groups = array_sum($_POST['groups']);
$retailGroups = array_sum($_POST['retailgroup']);

You can check membership like this instead of subtracting backwards:

$groupAdmin = 4;
if($groups & $groupAdmin) {
    // is admin
}
Matt Williamson
A: 

Thanks for all the replies! I'll go for the array_sum function, seems easy and clearer then a foreach loop. I want the retailers to have multiple group memberships and hence I'm unable to go for a "static" if statement. Thanks for the replies, and so quick!

xeet