未定义的变量:$ total = 0后总得失误;

时间:2018-02-28 03:19:55

标签: php arrays forms

我在PHP中遇到这个问题,当我得到中位数和平均值时,但当程序到达模式时它会显示错误:Undefined variable: total.

我尝试在函数开头声明$total = 0;,但它没有解决问题。

这是我的代码:

<?php
$number = ($_POST["name"]);
function mmmr($number, $output = \'mean\.'){
$total = 0;
if(!is_array($number)){
    return FALSE;
}else{
    switch($output){
        case \'mean\.':
            $count = count($number);
            $sum = array_sum($number);
            $total = $sum, $count;
        break;
        case \'median\.':
            rsort($number);
            $middle = round(count($number)  2);
            $total = $number[$middle-1];
        break;
        case \'mode\.':
            $v = array_count_values($number);
            arsort($v);
            foreach($v as $k => $v){$total = $k; break;}
        break;
        case \'range\.':
            sort($number);
            $sml = $number[];
            rsort($number);
            $lrg = $number[];
            $total = $lrg - $sml;
        break;
    }
    return $total;
    }
    }


   Mean = The average of all the numbers
   echo \'Mean: \.'.mmmr($number).\'
    \.';
   echo \'Mean: \.'.mmmr($number, \'mean\.').\'
    \.';

     Median = The middle value after the numbers are sorted smallest to largest
     echo \'Median: \.'.mmmr($number, \'median\.').\'
     \.';

      Mode = The number that is in the array the most times
        echo \'Mode: \.'.mmmr($number, \'mode\.').\'
      \.';

    Range = The difference between the highest number and the lowest number
    echo \'Range: \.'.mmmr($number, \'range\.');
  ?>

1 个答案:

答案 0 :(得分:0)

这里有很多语法错误 你可以尝试:

$number = [1,2,3,5];

function mmmr($number, $output = 'mean.') {
    $total = 0;
    if (!is_array($number)) {
        return FALSE;
    } else {
        switch ($output) {
            case 'mean.':
                $count = count($number);
                $sum = array_sum($number);
                $total = $sum+ $count;
                break;
            case 'median.':
                rsort($number);
                $middle = round(count($number), 2);
                $total = $number[$middle - 1];
                break;
            case 'mode.':
                $v = array_count_values($number);
                arsort($v);
                foreach ($v as $k => $v) {
                    $total = $k;
                    break;
                }
                break;
            case 'range.':
                sort($number);
                $sml = $number[0];
                rsort($number);
                $lrg = $number[0];
                $total = $lrg - $sml;
                break;
        }
        return $total;
    }
}

echo 'Mean: .' . mmmr($number) . '
    .';
echo 'Mean: .' . mmmr($number, 'mean.') . '
    .';


echo 'Median: .' . mmmr($number, 'median.') . '
     .';

echo 'Mode: .' . mmmr($number, 'mode.') . '
      .';


echo 'Range: .' . mmmr($number, 'range.');