PDA

View Full Version : avgval function



Zero-Affect
05-05-2010, 07:52 PM
I was watching Cube and came up with a idea for a function, i have no idea if it already exists though but it may come in helpful.

function avgval($avg_vals) {
if ( is_array($avg_vals) && count($avg_vals) > 1 ) {
$return_vals = ( array_sum($avg_vals) / count($avg_vals) );
} elseif ( is_array($avg_vals) && count($avg_vals) == 1 ) {
$return_vals = current($avg_vals);
} else {
$return_vals = FALSE;
}
return $return_vals;
}
echo avgval(array(6,11,7)); // outputs 8
echo avgval(array(6)); // outputs 6

Zero-Affect
05-06-2010, 12:47 PM
Also thought i'd make up another version which works on string rather than array (im sure the two could be collided).

function avgvals($avg_vals,$avg_delimiter=',') {
if ( (is_string($avg_vals) && strlen($avg_vals) > 2) && (is_string($avg_delimiter) && !empty($avg_delimiter)) ) {
$average_vals = explode($avg_delimiter, $avg_vals);
$return_vals = ( array_sum($average_vals) / count($average_vals) );
} elseif ( (is_string($avg_vals) && strlen($avg_vals) <= 2) && (is_string($avg_delimiter) && !empty($avg_delimiter)) ) {
$return_vals = $avg_vals;
} else {
$return_vals = FALSE;
}
return $return_vals;
}
echo avgvals('6,11,7'); // outputs 8
echo avgvals('6-11-7', '-'); // outputs 8
echo avgvals('6'); // outputs 6

Djkanna
05-06-2010, 03:36 PM
This could actually be quite handy.
Nice work Zero!

Zero-Affect
05-06-2010, 04:46 PM
I submitted them to php.net in notes so im sure people will use them.

Spudinski
05-09-2010, 09:09 PM
PHP isn't new, neither is mathematics - everything you will ever think of has been done before.
I find these two function to be more productive: http://www.mdj.us/web-development/php-programming/calculating-the-median-average-values-of-an-array-with-php/

Edit: Now that I think of it, why the hell doesn't PHP have an average or median function? When I learned Delphi my teacher drilled my with those functions(sqrt, cos and sin was more severe, but still).

Zero-Affect
05-10-2010, 06:22 AM
function calculate_average($arr) {
$count = count($arr); //total numbers in array
foreach ($arr as $value) {
$total = $total + $value; // total value of array numbers
}
$average = ($total/$count); // get average value
return $average;
}

compared to mine

function avgval($avg_vals) {
if ( is_array($avg_vals) && count($avg_vals) > 1 ) {
$return_vals = ( array_sum($avg_vals) / count($avg_vals) );
} elseif ( is_array($avg_vals) && count($avg_vals) == 1 ) {
$return_vals = current($avg_vals);
} else {
$return_vals = FALSE;
}
return $return_vals;
}
I'd say mine is better and more efficient really...

Yeah i published my notes on php.net hope they maybe adopt the functions in some way that would be nice.

rulerofzu
07-18-2010, 06:51 PM
Just so happens that earlier today I needed such a function. So thanks for this.

Zero-Affect
07-18-2010, 07:04 PM
Your welcome, glad i could help.