Jump to content

getting sum total from variable variables


newb

Recommended Posts

when $i = 4, im trying to get the sum of the values and store it in a variable but idk how. im using variable variables..

 

for($i = 0; $i < 5; $i++) {
$varname = 'testimonyletters_'.$i.'';
if (preg_match('|<td class="'.$i.' page" style="background-color:#ccc"><a href="'.$url.'">(.*)</a></td>
        <td class="'.$i.' sum">(.*)</td>|Ui',$stats,$result)) {
$$varname = $result[2];

}

if ($i == 4) {
$$varname = ($varname_1+$varname_2+$varname_3);
}
}

 

i would like the $testimonyletters_4 variable to be the sum of the previous variables 1-3. when $i == 4, my current code is not working. any idea how to fix this?

well i updated my code a bit and removed the variable variables and made a function instead.

 

function returnstats ($url,$name) {
global $stats;
echo '<tr>';
echo '<td width="" valign="top"><p>'.$name.'</p></td>';
for($i = 0; $i <=4 ; $i++) {
if (preg_match('|<td class="'.$i.' page" style="background-color:#ccc"><a href="'.$url.'">(.*)</a></td>
        <td class="'.$i.' sum">(.*)</td>|Ui',$stats,$result)) {
	echo '<td width="" valign="top"><p>'.$result[2].'</p></td>';
	}

	if ($i == 4) {			
	}
}
echo '</tr>';
}

 

so is it possible to get the total sum of previous data pulled from the preg_match result within the for loop or what?

fixed:

 

heres code if anyone runs into a similar problem:

function returnstats ($url,$name) {
global $stats;
echo '<tr>';
echo '<td width="" valign="top"><p>'.$name.'</p></td>';
$sum = 0;
for($i = 1; $i <=4; $i++) {
if (preg_match('|<td class="'.$i.' page" style="background-color:#ccc"><a href="'.$url.'">(.*)</a></td>
        <td class="'.$i.' sum">(.*)</td>|Ui',$stats,$result)) {
		switch ($i) {
		case 1:
		$sum1 = $result[2];
		break;
		case 2:
		$sum2 = $result[2];
		break;
		case 3:
		$sum3 = $result[2];
		break;
		default:
		$sum = $result[2];
		}

		$sum = $result[2];
}

if ($i == 4) {
$sum = $sum1+$sum2+$sum3;
}

echo '<td width="" valign="top"><p>'.$sum.'</p></td>';


}
echo '</tr>';
}

Why not simply initialize a variable outside the loop, then add to it inside the conditional in the loop to store a running total?

 

$total = '';
for( $i = 0; $i < 10; $i++ ) {
if( $i % 2 === 0 ) {
	$total += $i;
}
}
echo $total;

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.