Jump to content

Counting total of a variable in for loop


slyte33

Recommended Posts

Ok so let's say I have this:

 

for($i=1;$i<=5; $i++)
{
$rand = mt_rand(0, 10);
echo $rand;
echo "<br>";
}

 

As you can see, it will generate a random number 1-10 5 times.

What I want to do is get the total number recorded out of those randoms.

 

Let's say the outcome was this:

 

1

2

9

6

3

 

The total number = 21

 

All feedback appreciated, thanks :)

 

 

Thank you very much :)

 

I have another question if you don't mind now, what exactly does += do?

Does this mean I could count the total fields in a row of a mysql table too?

Example:

select * from something

while($something=$example->fetchrow())

{

$ex += $something[count_total_number_of_all_rows_in_field]

}

 

So basically += can be used in a for and while loop? :)

Does this mean I could count the total fields in a row of a mysql table too?

Example:

select * from something

 

MySQL supports aggregate functions that you can utilize such as SUM().  This would be faster than calculating the total in PHP.

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.