Given a file of data containing the heights and weights of a sample of students, analyse the data to find the mean, median and modal values.
<?
// displaying heights and weights is nearly identical
// so a function is used to avoid repeating code
// * array is the list of values
// * type is what the array is based on (like height)
// * measurement is what to show after the values (like pounds)
function ic_show_stats($array, $type, $measurement)
{
// display the type with the first letter capitalised
echo ucfirst($type) . ':<br/>';
// add up all the values in the array and divide by the number of values
echo '- Mean: ' . round(array_sum($array) / count($array), 2) . ' ' . $measurement . ' <br/>';
// sort the values into numerical order
sort($array);
// show the middle value
echo '- Median: ' . $array[count($array)/2] . ' ' . $measurement . ' <br/>';
// get the frequency of all the values in the array
$frequency = array_count_values($array);
// sort into reverse numerical order while maintaining keys
arsort($frequency);
// get the keys
$freq_keys = array_keys($frequency);
// show the first key (the one with the highest frequency)
echo '- Mode: ' . $freq_keys[0] . ' ' . $measurement . ' <br/>';
}
// the file containing all the data
$height_weight_file = file('littleredbook/8-2-data.txt');
// run through each line in the file
foreach ($height_weight_file as $line)
{
// separate using the separator char
$separate = explode(' ', $line);
// add the values to the arrays
$heights[] = $separate[0];
$weights[] = $separate[1];
}
// display the stats about each set of values
ic_show_stats($heights, 'heights', 'cm');
echo '<br/>';
ic_show_stats($weights, 'weights', 'pounds');
?>
Which produces for this data file:
Heights:
- Mean: 149.04 cm
- Median: 148 cm
- Mode: 142 cm
Weights:
- Mean: 119.28 pounds
- Median: 130 pounds
- Mode: 138 pounds