【问题标题】:PHP - Comparison of array element to input issuePHP - 数组元素与输入问题的比较
【发布时间】:2014-01-09 06:40:00
【问题描述】:

下面的代码有问题,我想根据文本文件中的值测试用户的输入。代码的输出仅适用于数组的最后一个元素(文本文件的每个值都存储为数组的一个元素),它成功地将输入与数组元素进行了正确比较,但是当在数组,没有进行“匹配”。我希望所有值都是数字,并且只有一个相同的值存在,如果超过一个,则输出错误。谢谢大家:)

array.txt 有以下内容

11111
22222
33333
44444

PHP:

<?PHP

if (isset($_REQUEST['attempt']))    {

$users = file('C:/wamp/www/php/comparision/array.txt');
$input = $_POST['input'];

print "Results:";
print '<br></br>';

$x = count($users);

print '<br></br>';
print '<br></br>';

$i = 0;

    while ($i < $x) {

        print $users[$i];
        print $input;
        $truevar = NULL;

        $arrayelement = $users[$i];

            if ($input == $arrayelement) {
                print '<p>';
                echo " It is in the array";
                print '</p>';
                $truevar = $truevar + 1;
            }
            else if ($input != $arrayelement) {
                print '<p>';
                echo " Nope";
                print '<p>';
            }

    print '<br></br>';

    $i = $i + 1;

    }

//Check entries

if ($truevar > 1)   {
    print '<br></br>';
    echo "Multiple entries";
}
else if ($truevar == 1) {
    print '<br></br>';
    echo "Comparison success";
}
else if ($truevar < 1)  {
    print '<br></br>';
    echo "Comparison not successfull";
}   

}
?>

<p>Please enter data</p><br></br>
<form action="compare.php?attempt" method="post"/>
<input type="text" name="input" size="15" value=""  />
<input type="submit" name="carddata" value="Submit"/>
</form>

【问题讨论】:

  • 文件内容是什么?您的问题在一行中包含所有数字,以- 分隔,而不是多行。对吗?
  • 尝试在调用file()时添加FILE_IGNORE_NEW_LINES选项
  • 我已经编辑了文件格式,每个系列的数字都换行了,很抱歉造成混乱。

标签: php


【解决方案1】:

用途:

$users = file('C:/wamp/www/php/comparision/array.txt', FILE_IGNORE_NEW_LINES);

如果没有该选项,分隔文件中各行的换行符将包含在 $users 中的值中,因此比较失败。

【讨论】:

    【解决方案2】:

    问题似乎是您在 while 循环内设置了$truevar = NULL;。像这样,变量总是在每次循环时重置为 NULL。

    如果您将$truevar = NULL 移到while-line 上方应该没问题

    【讨论】:

    • 愚蠢的我,这给条目检查带来了问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多