I have a form that has variables val1 through val20. I need to get a total based on adding up the variable values.
Originally I had a simple statement:
$svar = val1 + val2 + val3...+ val20;
For a cleaner solution I switched to:
$svar = 0;
for($n=1; $n<=20; $n++) {
$svar += ${"val". $n};
}
Now, what I would like to do is to be able to port this section to other pieces of code, so the number of form fields can be changed without having to touch the script. Something like this:
$svar = 0;
$n = 1;
while (isset(${"val". $n}) {
$svar += ${"val". $n++};
}
Unfortunately this gives me parse errors on the while line, and I am not sure why. Is this heading in the right direction, and what do I need to do to get rid of the parse errors?
Also -- someone suggested that an array might be more efficient, but I am not sure why, would you consider using an array for this process?
Thanks!