获取平均值的PHP算法


PHP arithmetic for getting average

我正在尝试练习PHP,遇到了这个问题,这只是一个简单的计算来获得平均值,但当我输入数字时,他们似乎给了我错误的答案。

<?php 
if(!empty($_POST['first'])&&$_POST['second']&&$_POST['third']&&$_POST['fourth']&&$_POST['fifth'])
  {
$first = $_POST['first'];
$second = $_POST['second'];
$third = $_POST['third'];
$fourth = $_POST['fourth'];
$fifth = $_POST['fifth'];
$average = array($first,$second,$third,$fourth,$fifth);
$total = 0;
foreach($average as $value){
    $total =+ $value;
}
 $the_average = $total/count($average);
    echo $the_average;

}else{
echo 'Please complete all fields';
 }
?>
 <html>
<head><title>Test run</title></head>
<body>
<form method="POST">
    Quizzes
    <input type='text' name="first" maxlength="2"> ,
    <input type='text' name="second" maxlength="2"> ,
    <input type='text' name="third" maxlength="2"> ,
    <input type='text' name="fourth" maxlength="2"> ,
    <input type='text' name="fifth" maxlength="2"> ,
    <input type="submit" value="submit" >
</form>

<?php 
if(!empty($_REQUEST['first']) && $_REQUEST['second'] && $_REQUEST['third'] && $_REQUEST['fourth'] && $_REQUEST['fifth'])
  {
$first = $_REQUEST['first'];
$second = $_REQUEST['second'];
$third = $_REQUEST['third'];
$fourth = $_REQUEST['fourth'];
$fifth = $_REQUEST['fifth'];
$average = array($first,$second,$third,$fourth,$fifth);
$total = array_sum($average);
$the_average = $total/count($average);
echo $the_average;
}else{
echo 'Please complete all fields';
}
?>

我们假设$first到$fifth可能是string,所以让我们尝试将其设为flot

<?php
    $first = $_POST['first'];
    $second = $_POST['second'];
    $third = $_POST['third'];
    $fourth = $_POST['fourth'];
    $fifth = $_POST['fifth'];
    $average = array($first,$second,$third,$fourth,$fifth);
    $total = floatval(0);
    foreach($average as $value){
        $total =+ floatval($value);
    }
    $the_average = floatval($total)/count($average);
    echo number_format(floatval($the_average),2, '.', '');
?>