Jump to content

Totalling up a looping number from variable


Mutley

Recommended Posts

I have a simple function that will repeat several times but attach a number to a variable:

$number;

 

each time it runs, this number changes as it loops around, all I would like is to add these together and attach the total after it stops looping to a new variable.

 

How would I do this? Using a foreach or making a counting variable?

 

Thanks,

Nick.

Say if I have a function:

 

function randomNum() {
$number = rand(1,10);
echo $number;
}

// Would echo:
4
5
8
2

 

And it loops 10 times (not sure how I would, say a query was inside it instead and it got several results from the same field).

 

How would I add all the $numbers echoed together? So it said "19" in the above example?

 

Maybe

 

function randomNum() {
$number = rand(1,10);
return $number;
}

$sum = 0;
for($i=1;$i<=10;$++) {
echo $number = randomNum();
$sum = $sum + $number;
}

 

And it loops 10 times (not sure how I would, say a query was inside it instead and it got several results from the same field).

 

How would I add all the $numbers echoed together? So it said "19" in the above example?

 

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.