Hướng dẫn find median php


$test = array(
    array(5,2,1,3,4),
    array(),
    array(1)
);
foreach($test as $arr){
    $count = count($arr);
    sort($arr);
    $mid = floor(($count-1)/2);
    $avg = ($arr)?array_sum($arr)/$count:0;
    $median = ($arr)?($arr[$mid]+$arr[$mid+1-$count%2])/2:0;
    echo 'avg: '.$avg."
"; echo 'median: '.$median."
"; } ?>


function median($arr){
    if($arr){
        $count = count($arr);
        sort($arr);
        $mid = floor(($count-1)/2);
        return ($arr[$mid]+$arr[$mid+1-$count%2])/2;
    }
    return 0;
}
function average($arr){
    return ($arr) ? array_sum($arr)/count($arr) : 0;
}
$test = array(
    array(5,2,1,3,4),
    array(5,4,2,3,1,6),
    array(),
    array(1),
    array(2,4),
); 
foreach($test as $arr){
    echo 'avg: '.average($arr)."
"; echo 'median: '.median($arr)."
"; } ?>

Be careful about how you write your for() loop. If you want 30 entries, then you should not use <= or you will end up with 31 because $i starts with 0.

Build an array of the random numbers, then sort them.

Then determine if you have a central entry (odd array length) or if you need to average the middle two entries (even array length).

Here is a modern implementation of a median method posted in 2022 on CodeReview.

Code: (Demo)

$limit = 30;  // how many random numbers do you want?  30 or 31?
for ($i = 0; $i < $limit; ++$i) {
    $numbers[] = rand(0, 100);
}
var_export($numbers);

//echo "\n---\nAverage: " , array_sum($numbers) / $limit;
echo "\n---\n";

sort($numbers);
$count = sizeof($numbers);   // cache the count
$index = floor($count/2);  // cache the index
if (!$count) {
    echo "no values";
} elseif ($count & 1) {    // count is odd
    echo $numbers[$index];
} else {                   // count is even
    echo ($numbers[$index-1] + $numbers[$index]) / 2;
}

Possible Output:

array (
  0 => 27,
  1 => 24,
  2 => 84,
  3 => 43,
  4 => 8,
  5 => 51,
  6 => 60,
  7 => 86,
  8 => 9,
  9 => 48,
  10 => 67,
  11 => 20,
  12 => 44,
  13 => 85,
  14 => 6,
  15 => 63,
  16 => 41,
  17 => 32,
  18 => 64,
  19 => 73,
  20 => 43,
  21 => 24,
  22 => 15,
  23 => 19,
  24 => 9,
  25 => 93,
  26 => 88,
  27 => 77,
  28 => 11,
  29 => 54,
)
---
43.5

After sorting, elements [14] and [15] hold 43 and 44 respectively. The average of these "middle two" values is how the result is determined. (Hardcoded numbers demo)


If you want a short, inflexible, hardcoded snippet, then you can use 30 and 14 and 15 as your predetermined size and indexes.

for ($i = 0; $i < 30; ++$i) {
    $numbers[] = rand(0, 100);
}
sort($numbers);
echo ($numbers[14] + $numbers[15]) / 2;