无论输入如何,函数总是返回true

时间:2016-05-21 08:42:08

标签: php forms

我尝试创建一个将字符串中的第一个数字与状态匹配的函数。例如,如果用户输入以3开头的数字和状态“vic”,则表单不应出现任何错误。但无论输入什么,函数始终返回true。任何帮助将不胜感激。

$state = array('Please Select', 'VIC', 'NSW', 'QLD', 'NT', 'WA', 'SA', 'TAS', 'ACT'); //In the form this is a drop down menu

$selected_key = $_POST['state'];

$postcode = $_POST["postcode"]; //The full number entered by the user

$errMsg .= validatePS($postcode, $selected_key);

function validatePS($ps, $state) {

$errMsg ="";
$digit = $ps[0]; //Takes the first number from full postcode
$valid = false;

if (($digit == 3) or ($digit == 8) && ($state == 'vic'))
{
   $post = true;
}

if (($digit == 1) or ($digit == 2) && ($state == 'nsw'))
{
   $post = true;
}

if (($digit == 4) or ($digit == 9) && ($state == 'qld'))
{
   $post = true;
}

if ($valid == false) {
   $errMsg .= "<p>Match the correct postcode to state</p>";
}

return $errMsg;

}

if ($errMsg !=""){
   echo "<p>Please correct the following errors...</p>"; //Prints out errors
   echo "<p>$errMsg</p>";
}

1 个答案:

答案 0 :(得分:0)

你有两个&#34; flag&#34;您要更新的变量 - $post和您依赖的$valid。如果将它们减少为一个变量,则应该得到所需的行为:

function validatePS($ps, $state) {
    $errMsg ="";
    $digit = $ps[0]; //Takes the first number from full postcode
    $valid = false;

    if (($digit == 3) or ($digit == 8) && ($state == 'vic'))
    {
        $valid = true;
    }

    if (($digit == 1) or ($digit == 2) && ($state == 'nsw'))
    {
        $valid = true;
    }

    if (($digit == 4) or ($digit == 9) && ($state == 'qld'))
    {
        $valid = true;
    }

    if ($valid == false) {
        $errMsg .= "<p>Match the correct postcode to state</p>";
    }

    return $errMsg;
}

请注意,您可以使用逻辑运算符而不是多个if语句来显着清理此代码:

function validatePS($ps, $state) {
    $errMsg ="";
    $digit = $ps[0]; //Takes the first number from full postcode
    $valid = false;

    if ((($digit == 3) or ($digit == 8) && ($state == 'vic')) ||
        (($digit == 1) or ($digit == 2) && ($state == 'nsw')) ||
        (($digit == 4) or ($digit == 9) && ($state == 'qld'))) {
        $errMsg .= "<p>Match the correct postcode to state</p>";
    }

    return $errMsg;
}