如何获得奇数,偶数和回输无效输入的总值

时间:2013-10-27 08:23:20

标签: php arrays

以下是我目前为其中一项作业提供的代码。

<!DOCTYPE html>
<html>
<head><title>Numbers</title></head>
<body>
<form action="index.php" method="get">
<b>Numbers</b>
<br>
<textarea rows="12" cols="25" name="result" value="result"></textarea>
<br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>

<?php
    $result=$_GET["result"];
    if (empty($_GET['result']))
        {
            echo '<p><font size="3" color="red">Field is Empty*</font></p>';
        }
    elseif (isset($_GET['result']))
        {
            $result=(explode("\n", $result));
        }

    echo "<br />";  
    echo "Total lines passed: " . count ($result);
    echo "<br />";
    echo "Total value of numbers: " .array_sum($result);

?>

我需要一个代码来回显提交到文本框中的偶数和奇数输入的总值。防爆。提交了1,2,3,4,5,并且偶数的总值为6,因为2和4是偶数,奇数的总值为9,因为1,3和5是奇数。如果用户也输入了无效的整数,那么假设a,b,c。我将能够回显出所有提交的无效值的列表。

1
2
3
4
5
a
b
c

Total of even numbers: 6
Total of odd numbers: 9
Invalid Numbers: a b c

4 个答案:

答案 0 :(得分:2)

$result = array_map('trim', $result); // to trim the whitespace in your input
$even = $odd = $invalid = array();

foreach ($result as $num) {        
    if (is_numeric($num)) {
        if ($num % 2 == 0) {
            $even[] = $num;
        } else {
            $odd[] = $num;
        }
    } else {
        $invalid[] = $num;
    }
}

echo "Total of even numbers: " . array_sum($even) . "<br />";
echo "Total of odd numbers: " . array_sum($odd) . "<br />";
echo "Invalid numbers: " . implode(' ', $invalid) . "<br />";

Demo!

答案 1 :(得分:0)

试试:

$even=array();
$odd=array();
$invalid=array();
for($i=0;$i<count($result);$i++)
{
   if(!is_numeric($result[$i])) { $invalid[]=$result[$i]; continue; }
   if($result[$i] % 2 == 0) $even[]=$result[$i];
   else $odd[]=$result[$i];
}
echo "Sum of even numbers: " . array_sum($even);
echo "Number of even numbers: " . count($even);
echo "Sum of odd numbers: " . array_sum($odd);
echo "Invalid numbers: " . implode(",",$invalid);

答案 2 :(得分:0)

$total = array("even" => 0, "odd" => 0, "invalid" => 0);

foreach ($result as $r){
    if(intval($r) == "" && $r != 0){
        $total['invalid']++; 
    }else{
        if ($r % 2 == 0){
            $total['even'] += $r;
        }else{
            $total['odd'] += $r;
        }
    }
}

print_r($total);

答案 3 :(得分:0)

试试这个:

    $evenSum=0;$oddSum=0;
    $alphaArr=array();
    foreach($result as $key){
    if(!is_nan($key)){
    if($key%2==0){
    $evenSum+=$key;
    }
    else{
    $oddSum+=$key;
    }
    }else{
   $alphaArr[]=$key;