Jump to content

sum unknown number of post fields


lindm

Recommended Posts

I am trying to make a script that does the following:

 

Say I have x number of fields in a form named like the following:

FieldA1y

FieldA1x

FieldA2y

FieldA2x

FieldA3y

FieldA3x

etc etc

FieldASUMy

FieldASUMx

 

The script should calculate a sum for all fields with beginning with FieldA and ending with y as one sum and beginning with FieldA and ending with x as one sum. The field FieldASUMX or y should not be included in the sum. Not much I got so far:

 

function sum($field) {
$total = 0;

//code

return $calc[$field] = $total;	
}

The script would be called like sum("FieldASUMx"). This would sum all fields beginning with FieldA and ending with x, however not the FieldASUMx field.

Link to comment
Share on other sites

Went through the array functions at http://www.w3schools.com/PHP/php_ref_array.asp but can't find a good function for me. Code to explain:

<?php

$_POST=array( 
"RRintNOcy" => "1", 
"RRintNOpy" => "2", 
"RRintVLcy" => "3", 
"RRintVLpy" => "4", 
"RRintSUMcy" => "5", 
"RRintSUMpy" => "6" 
); 
function sum() {
return array_sum($_POST[only values of keys beginning with RRint and ending with cy AND not containing SUM);
}
echo sum();
?>

Should return 4.

Link to comment
Share on other sites

Understand. Since I need to use the id tag for all my text fields (jquery) each text field still needs to be unique. This is the code I currently use. Is it slow for larger forms/is there more efficient code?

$_POST=array( 
"RRintNOcy" => "1", 
"RRintNOpy" => "2", 
"RRintVLcy" => "3", 
"RRintVLpy" => "4", 
"RRintSUMcy" => "5", 
"RRintSUMpy" => "6" 
); 


function sum($name,$yr){
$total = 0;

foreach ($_POST as $k => $v) {
		if(substr($k,0,-4)==$name&&substr($k,-2)==$yr){
            $total += $v;
	}
}	
return $total; 

}
echo sum(RRint,cy);

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.