fou2enve Posted May 22, 2007 Share Posted May 22, 2007 I am writing an auditing script for a friend that runs a motel. He's got all the data in a mysql database. He wants to see what his average room rate he's been giving his customers. I've got this so far: function average($arr) { if (!is_array($arr)) return false; return array_sum($arr)/count($arr); } $array = array($Room101Rate, $Room102Rate, $Room103Rate); echo average($array); but I want this to be completely automated, but the problem is that I have all the rooms in the array (i only included three, but there are 40 total, you get the idea) heres the problem, if room 102 and 103 have not been sold I get a result of 0 for those rooms. This on a large scale could affect the average drastically. So how can I calculate the average correctly? Any help is appreciated. thanks. Quote Link to comment https://forums.phpfreaks.com/topic/52487-solved-help-with-averaging/ Share on other sites More sharing options...
taith Posted May 22, 2007 Share Posted May 22, 2007 not tested... but it should work :-) function average($arr){ if(!is_array($arr)) return false; return array_sum($arr)/count($arr); } function cleanup($array){ $out=array(); foreach($array as $k=>$v){ if(!empty($array[$k])) $out[$k]=$v; } return $out; } $array=cleanup(array('134.32', '', '123.12')); echo average($array); Quote Link to comment https://forums.phpfreaks.com/topic/52487-solved-help-with-averaging/#findComment-258984 Share on other sites More sharing options...
kenrbnsn Posted May 22, 2007 Share Posted May 22, 2007 You can add the rates into the array in a loop that retrieves all the rooms with a non-zero rate: <?php $q = "select roomrate from YourTable where roomrate > 0"; $rs = mysql_query($q); $rr = array(); while ($row = mysql_fetch_assoc($rs)) $rr[] = $row['roomrate']; echo average($rr); ?> Or you can let MySQL do all the work: <?php $q = "select sum(roomrate) as s_rm, count(roomrate) as c_rm where roomrate > 0"; $rs = mysql_query($q) $rw = mysql_fetch_assoc($rs); $echo $rw['s_rm'] / $rw['c_rm']; ?> Please note that my MySQL syntax maybe slightly off. Ken Quote Link to comment https://forums.phpfreaks.com/topic/52487-solved-help-with-averaging/#findComment-258989 Share on other sites More sharing options...
fou2enve Posted May 22, 2007 Author Share Posted May 22, 2007 Thank you both. Taith I ended up using your solution. Thanks again Quote Link to comment https://forums.phpfreaks.com/topic/52487-solved-help-with-averaging/#findComment-258991 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.