I have a bunch a values I would like to add together which are entered into a form. Right now, the form has 11 lines but it could get larger in the future. I can easily add
The values you need are posted from a form, right? If so, you could iterate through the keys in the $_POST variable that match your form field's generated names.
foreach($_POST as $key=>$value)
{
if(strpos($key, 'pBalance')===0)
{
$final_total += $value;
}
}
for ($i = 1 ; $i <= 3 ; $i++){
$varName = "pBalance".$i;
$tempTotal += $$varName;
}
This will do what you want. However you might indeed consider using an array for this kind of thing.
In about 99% of all cases involving a PHP generated variable, you are doing The Wrong Thing. I'll just re-iterate what others have said:
USE AN ARRAY
Uhm why don't you use an array? If you give the forms a name like foobar[] it will be an array in PHP.
If you're trying to collect the values of a POST, you should really use an array. You can avoid having to manually piece together such an array by using:
<input type="text" name="vals[]" value="one" />
<input type="text" name="vals[]" value="two" />
$_POST["vals"]
will then be array("one", "two");
I would use @unexist's solution.. give the input fields names like:
<input name="myInput[]" />
<input name="myInput[]" />
<input name="myInput[]" />
...
Then in your PHP get the sum like this:
$total = array_sum($_REQUEST['myInput']);
Because of the '[]' at the end of each input name, PHP will make $_REQUEST['myInput'] automatically be an array. A handy feature of PHP!