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
https://forums.phpfreaks.com/topic/188384-sum-unknown-number-of-post-fields/
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.

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);

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.