Average

By F*U*R*B*Y* on Jul 30, 2008

just a simple function that will get the average of numbers that you picked...

Useage: $numbers = "1 4 9 10 4 8"; average($numbers);

and will return the average of them numbers ;)

<?php
// For those that don't like using explode

function average($numbers) {
   $a = split(' ', $numbers);
   foreach ($a as $b) { $c = $c + $b; $d++; }
   return number_format($c/$d,0);
}

// For those that like using explode

function average($numbers) {
   $a = explode(' ', $numbers);
   $d = count($a);
   for ($i=$d;$i;$i--) { $c = $c + $a[$i]; }
   return number_format($c/$d,0);
}

?>

Comments

Sign in to comment.
F*U*R*B*Y*   -  Aug 29, 2008

i dont care which is faster, i care about which one i understand more, then i use the opposite and learn how the other one works ;)

 Respond  
markusPHP   -  Aug 28, 2008

There should be no preference between split() and explode(); explode IS faster.

 Respond  
F*U*R*B*Y*   -  Aug 01, 2008

updated to show people how to use explode instead of using split

 Respond  
Hawkee   -  Jul 31, 2008

Only problem is a list of numbers usually won't be stored in a single string like that. More than likely I'll use mySQL to avg() a field for me.

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.