rwilson Posted July 8, 2007 Share Posted July 8, 2007 if i have an array like $book = array("newbook" => array(10, 20, 30), "usedbook" => array(15, 25, 35)); and i want to average the three numbers for each book, how do i do it? i've tried several ways already and they don't work. i want them to print out using a loop. like, col. 1 col. 2 new book 30 used book 25 Quote Link to comment Share on other sites More sharing options...
Yesideez Posted July 8, 2007 Share Posted July 8, 2007 <?php $arr=array("newbook" => array(10, 20, 30), "usedbook" => array(15, 25, 35)); $newbooktotal=0; $usedbooktotal=0; foreach ($arr['newbook'] as $newbook) { $newbooktotal+=$newbook; } foreach ($arr['usedbook'] as $usedbook) { $usedbooktotal+=$usedbook; } echo 'Averages:<br />New='.$newbooktotal/count($arr['newbook']).'<br />Used='.$usedbooktotal/count($arr['usedbook']); ?> I think thats about right... Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted July 8, 2007 Share Posted July 8, 2007 Perhaps a shorter way to do it: <?php $book = array("newbook" => array(10, 20, 30), "usedbook" => array(15, 25, 35)); foreach($book as $key => $value){ $average = array_sum($value) / count($value); echo "Average of: $key = $average <br />"; } ?> Quote Link to comment Share on other sites More sharing options...
Yesideez Posted July 8, 2007 Share Posted July 8, 2007 Darn! I keep forgetting about those brilliant array functions! Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted July 8, 2007 Share Posted July 8, 2007 Haha, i was annoyed there wasn't an array_average() function built in Quote Link to comment 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.