In what scenarios is the median a better estimation measure than the average for sensor data in PHP?

When dealing with sensor data in PHP, the median can be a better estimation measure than the average in scenarios where the data contains outliers or extreme values that could skew the average. The median is less affected by outliers because it represents the middle value in a sorted dataset, whereas the average includes all values in its calculation. By using the median, you can get a more accurate representation of the central tendency of the data.

// Function to calculate the median of an array of sensor data
function calculateMedian($data) {
    sort($data);
    $count = count($data);
    $middle = floor(($count - 1) / 2);

    if ($count % 2 == 0) {
        $median = ($data[$middle] + $data[$middle + 1]) / 2;
    } else {
        $median = $data[$middle];
    }

    return $median;
}

// Example sensor data
$sensorData = [12, 15, 17, 20, 22, 1000];

// Calculate the median of the sensor data
$median = calculateMedian($sensorData);

echo "Median: " . $median;