slyte33 Posted December 3, 2009 Share Posted December 3, 2009 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 Link to comment https://forums.phpfreaks.com/topic/183857-counting-total-of-a-variable-in-for-loop/ Share on other sites More sharing options...
cags Posted December 3, 2009 Share Posted December 3, 2009 $total = 0; for($i=1;$i<=5; $i++) { $rand = mt_rand(0, 10); echo $rand; echo "<br>"; $total += $rand; } echo $total; Link to comment https://forums.phpfreaks.com/topic/183857-counting-total-of-a-variable-in-for-loop/#findComment-970537 Share on other sites More sharing options...
Maq Posted December 3, 2009 Share Posted December 3, 2009 Have a variable outside the loop that can tabulate the total. $total = 0; for($i=1;$i{ $rand = mt_rand(0, 10); echo $rand; $total += $rand; echo " "; } Link to comment https://forums.phpfreaks.com/topic/183857-counting-total-of-a-variable-in-for-loop/#findComment-970540 Share on other sites More sharing options...
slyte33 Posted December 3, 2009 Author Share Posted December 3, 2009 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? Link to comment https://forums.phpfreaks.com/topic/183857-counting-total-of-a-variable-in-for-loop/#findComment-970543 Share on other sites More sharing options...
cags Posted December 3, 2009 Share Posted December 3, 2009 $a += $b means $a = $a + $b. Link to comment https://forums.phpfreaks.com/topic/183857-counting-total-of-a-variable-in-for-loop/#findComment-970547 Share on other sites More sharing options...
Maq Posted December 3, 2009 Share Posted December 3, 2009 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. Link to comment https://forums.phpfreaks.com/topic/183857-counting-total-of-a-variable-in-for-loop/#findComment-970552 Share on other sites More sharing options...
slyte33 Posted December 3, 2009 Author Share Posted December 3, 2009 Thanks Link to comment https://forums.phpfreaks.com/topic/183857-counting-total-of-a-variable-in-for-loop/#findComment-970583 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.