I'm writing a script that works out the mode, median and mean of a set of data. I have ten records which are stored in a MySQL database and in a PHP array. When the script is finished, the script will only use the data stored in the database and not the PHP array, the PHP array is there to test the code.
What I have found though is that the results are different when using the PHP array compared to the MySQL array. In the PHP array, I have the following data:
$arr = array(60, 70, 71, 76, 144, 151, 197, 229, 233, 233);
In my MySQL database, I have this code:
$data = mysql_query("SELECT amount FROM example") or die(mysql_error());
$arr = mysql_fetch_array($data);
The data is the same, the exception being that the MySQL data contains .00 after each record. During the time spent trying to find out why it was giving the wrong results, I removed the .00 from each record in the database. The data is still wrong though.
The results, when using the PHP array gives me the following (correct) results:
Average (mean) value of payments £146.4
Payments values that occur most often £233
Median value of payments £151
The results, when using the MySQL array gives me the following (wrong) results:
Average (mean) value of payments £144
Payments values that occur most often £144
Median value of payments £144
I'm at a loss to explain why this is happening. Below is the PHP code I'm using to generate these results:
<?php
function arithmetic($array, $output = 'mean'){
switch($output){
// This case works out the mean
case 'mean':
$count = count($array);
$sum = array_sum($array);
$total = $sum / $count;
break;
// This case works out the median
case 'median':
rsort($array);
$middle = round(count($array) / 2);
$total = $array[$middle-1];
break;
// This case works out the mode
case 'mode':
$v = array_count_values($array);
arsort($v);
foreach($v as $k => $v){$total = $k; break;}
break;
}
return $total;
}
// PHP Array with data
//$arr = array(60, 70, 71, 76, 144, 151, 197, 229, 233, 233);
// MySQL Connection & Retrieval of data
$data = mysql_query("SELECT amount FROM example") or die(mysql_error());
$arr = mysql_fetch_array($data);
?>
Anyone have any ideas?
UPDATE:
I've been playing the MySQL query, and using the following code:
$data = mysql_query("SELECT * FROM example") or die(mysql_error());
$arr = mysql_fetch_assoc($data);
print_r ($arr);
It displays the following, only result:
Array ( [id] => 1 [amount] => 144 )
So really, the query is bringing all of the records and not just the one.
$middle = (count($array) + 1) / 2; if (is_int($middle)) { $total = array[$middle - 1]; } else { $total = ($array[round($middle)] + $array[round($middle - 1)]) / 2; }