使用for循环替换if语句

时间:2013-10-06 00:06:14

标签: php

我正在试图找出如何使用for循环来循环数组并测试两个条件。我已经用foreach循环完成了它,但试图用for循环完成它。下面是我一直在研究的if块和for循环。

        if (empty($scores[0]) ||
        empty($scores[1]) ||
        empty($scores[2]) ||
        !is_numeric($scores[0]) ||
        !is_numeric($scores[1]) ||
        !is_numeric($scores[2])) {
            $scores_string = 'You must enter three valid numbers for scores.';
            break;
    }

这是HTML和PHP。

HTML:

<form action="." method="post">
    <input type="hidden" name="action" value="process_scores" />

    <label>Choose action:</label><br />
    <input class="radio" type="radio" name="calculate" value="average" checked="checked">Average<br />
    <input class="radio" type="radio" name="calculate" value="total">Total<br />
    <input class="radio" type="radio" name="calculate" value="both">Both<br />

    <label>Score 1:</label>
    <input type="text" name="scores[]"
           value="<?php echo $scores[0]; ?>"/><br />

    <label>Score 2:</label>
    <input type="text" name="scores[]"
           value="<?php echo $scores[1]; ?>"/><br />

    <label>Score 3:</label>
    <input type="text" name="scores[]"
           value="<?php echo $scores[2]; ?>"/><br />

    <label>&nbsp;</label>
    <input type="submit" value="Process Scores" /><br />

    <label>Scores:</label>
    <span><?php echo $scores_string; ?></span><br />

    <label>Score Total:</label>
    <span><?php echo $score_total; ?></span><br />

    <label>Average Score:</label>
    <span><?php echo $score_average; ?></span><br />
</form>

PHP:

if (isset($_POST['action'])) {
$action =  $_POST['action'];
} else {
$action =  'start_app';
}

switch ($action) {
case 'start_app':
    $scores = array();
    $scores[0] = 70;
    $scores[1] = 80;
    $scores[2] = 90;
    break;
case 'process_scores':
    $scores = $_POST['scores'];


    // validate the scores
    for ($i = 0; $i < count($scores); $i++) {
        if (empty($scores[$i]) || !is_numeric($scores[$i])) {
        $scores_string = 'You must enter three valid numbers for scores.';
        break;
        }
    }


    // process the scores
    $scores_string = '';
    foreach ($scores as $s) {
        $scores_string .= $s . '|';
    }
    $scores_string = substr($scores_string, 0, strlen($scores_string)-1);

    // Radio buttons
    $calculate_type = $_POST['calculate'];

    switch ($calculate_type) {
        case 'average':
            $score_tally = $scores[0] + $scores[1] + $scores[2];
            $score_average = $score_tally / count($scores);
            $score_average = number_format($score_average, 2);
            break;
        case 'total':
            $score_total = $scores[0] + $scores[1] + $scores[2];
            $score_total = number_format($score_total, 2);              
            break;
        case 'both':
            $score_tally = $scores[0] + $scores[1] + $scores[2];
            $score_average = $score_tally / count($scores);
            $score_total = $scores[0] + $scores[1] + $scores[2];
            $score_total = number_format($score_total, 2);
            $score_average = number_format($score_average, 2);
            break;
    }

    break;
case 'process_rolls':
    $number_to_roll = $_POST['number_to_roll'];

    $total = 0;
    // $count = 0;
    $max_rolls = -INF;

    for ($count = 0; $count < 1000; $count++) {
        $rolls = 1;
        while (mt_rand(1, 6) != 6) {
            $rolls++;
        }
        $total += $rolls;
        $max_rolls = max($rolls, $max_rolls);
    }
    $average_rolls = $total / $count;

    break;


}

使用此for循环验证分数到位,当存在无效数据时,我不会产生任何结果。

4 个答案:

答案 0 :(得分:2)

我会看看array_reduce,因为那基本上就是你正在做的事情:将数组减少为布尔值。

if( array_reduce(
   $scores,
   function($a,$b) {return $a || empty($b) || !is_numeric($b);},
   false)) {
       $scores_string = "You must enter three valid numbers for scores.";
}

答案 1 :(得分:2)

因为您要求for循环:

for ($i = 0; $i < count($scores); $i++)
    if (empty($scores[$i]) || !is_numeric($scores[$i])) {
        $scores_string = 'You must enter three valid numbers for scores.';
        break;
    }

答案 2 :(得分:1)

我不明白你为什么要测试得分是否为emtpy。如果得分为空,则is_numeric返回false。

我的for循环版本:

for ($i = 0, $len = count($scores); $i < $len and is_numeric($scores[$i]); $i++) {}
if ($i !== $len) echo 'You must enter three valid numbers for scores.';

编辑: 如果你需要测试数组中是否有3个数字项(如@geomagas建议的那样),那么:

for ($i = 0; $i < 3 and is_numeric($scores[$i]); $i++) {}

// If $i is less then 3 it's mean that one of items are not set or it's not numeric
if ($i < 3) echo 'You must enter three valid numbers for scores.';

编辑: 处理数组没有正确索引的情况的第三种解决方案。我发布这个只是为了好玩,拒绝使用empty函数@geomagas强迫我;)

$scores = array('234', '52', '245');

for (reset($scores); $valid = is_numeric(current($scores)) and next($scores);) {}

if ( ! $valid) echo 'You must enter three valid number for scores.';

答案 3 :(得分:0)

不应使用

empty(),因为0被认为是空的,也是数字。

$size = count($scores);
for ($i = 0; $i < $size; $i++) {
    if (!is_numeric($scores[$i])) {
        $scores_string = 'You must enter three valid numbers for scores.';
        break;
    }
}