Mutley Posted November 13, 2008 Share Posted November 13, 2008 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. Link to comment https://forums.phpfreaks.com/topic/132620-totalling-up-a-looping-number-from-variable/ Share on other sites More sharing options...
Mchl Posted November 13, 2008 Share Posted November 13, 2008 Static variables maybe? I'm not sure if I understood you correctly. Link to comment https://forums.phpfreaks.com/topic/132620-totalling-up-a-looping-number-from-variable/#findComment-689600 Share on other sites More sharing options...
Mutley Posted November 13, 2008 Author Share Posted November 13, 2008 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? Link to comment https://forums.phpfreaks.com/topic/132620-totalling-up-a-looping-number-from-variable/#findComment-689610 Share on other sites More sharing options...
Mchl Posted November 13, 2008 Share Posted November 13, 2008 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? Link to comment https://forums.phpfreaks.com/topic/132620-totalling-up-a-looping-number-from-variable/#findComment-689632 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.