Forum Moderators: coopster

Message Too Old, No Replies

adding fields

         

mattennant

12:06 am on Jan 17, 2008 (gmt 0)

10+ Year Member



i'm trying to add a bunch of fields in simple manner, basically i'm want in this


$ha_total = ($row_diary['ha1'] + $row_diary['ha2'] + $row_diary['ha3'] + $row_diary['ha4'] + $row_diary['ha5'] + $row_diary['ha6'] + $row_diary['ha7'] + $row_diary['ha8'] + $row_diary['ha9'] + $row_diary['ha10'] + $row_diary['ha11'] + $row_diary['ha12'] + $row_diary['ha13'] + $row_diary['ha14'] + $row_diary['ha15'] + $row_diary['ha16'] + $row_diary['ha17'] + $row_diary['ha18'] + $row_diary['ha19'] + $row_diary['ha20']) ;

in a more economical way
i've been playing with for loops, but no success


for ( $x = 1; $x <= 20; $x++){

$ha_total =
+ ($row_diary['ha'.$x ]) ;

}

any help as always appreciated

cameraman

12:44 am on Jan 17, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You've very nearly got it, just change this:
$ha_total =
+ ($row_diary['ha'.$x ]) ;

to:
$ha_total += $row_diary['ha'.$x ];
OR
$ha_total = $ha_total + $row_diary['ha'.$x ];

The first is just a shorthand way of accomplishing the second.
And you'd most likely want to set $ha_total to zero above the for loop.

mattennant

7:30 am on Jan 17, 2008 (gmt 0)

10+ Year Member



Thanks camerman

Help much appreciated

to build on that i have this situation happening


$ha_total1 = 0;
for ( $x = 1; $x <= 20; $x++){
$ha_total1 += $row_diary1['ha'.$x ];
}

$ha_total2 = 0;
for ( $x = 1; $x <= 20; $x++){
$ha_total2 += $row_diary2['ha'.$x ];
}

$ha_total3 = 0;
for ( $x = 1; $x <= 20; $x++){
$ha_total3 += $row_diary3['ha'.$x ];
}

Is it possible to bring for loop into a for loop
maybe something like


for ( $y = 1; $y <= 20; $y++){
$ha_total.$y = 0;
for ( $x = 1; $x <= 20; $x++){
$ha_total . $y += $row_diary . $y['ha'.$x ];
}
}

or is that over ambitious

cameraman

6:12 pm on Jan 17, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That's not overly ambitious at all. You'll need to use variable variables [php.net] to refer to the diaryx arrays.
You could set up the totals as separate variables and refer to them with variable variables as well, but I think you'll find that it's easier to deal with one $ha_total as an array:

for($y = 1; $y <= 20; $y++) {
$ha_total[$y] = 0;
for($x = 1; $x <= 20; $x++) {
$diary = 'row_diary' . $y;
$ha_total[$y] += ${$diary}['ha'.$x];
}
}

You can refer to the diary array without building a variable for it ($diary above goes away):
$ha_total[$y] += ${'row_diary'.$y}['ha'.$x];