PHP -比较表单值和数组值



我正试图编写一个代码,比较从文本文档的值与已从表单发布的值。

到目前为止,我得到了这个,但我绝对肯定我做的事情是错误的。

提前感谢您的帮助!

<form method="POST" action="file.php"> 
<p>
<br /><input type="text" name="name" ><br />
</p>
<p><input type="submit" value="Check" /></p>
</form>
<?php
if (isset($_POST['name'])) {
    $name = $_POST['name'];
    /*The text document contains these written names: 
    Michael 
    Terry 
    John 
    Phillip*/ 
    $lines = file('names.txt'); 
    $names_array = ($lines);   
        if (in_array($name, $names_array)) {
            echo "exists";
        } else {
            echo 'none';
        }
}
?>

更新:修复,现在工作正常!

问题是您的file('names.txt')函数。虽然这返回的数组每行都有一个单独的键,但它还在同一行上包含换行符。

那么你的数组实际上包含:

$lines[0] = "Michaeln";
$lines[1] = "Terryn";
$lines[2] = "Johnn";
$lines[3] = "Phillipn";

要防止这种情况发生,请使用file('names.txt', FILE_IGNORE_NEW_LINES)

$lines[0] = "Michael";
$lines[1] = "Terry";
$lines[2] = "John";
$lines[3] = "Phillip";

现在你的名字应该匹配了。

除此之外,你为什么用下面的?

$lines = file('names.txt'); 
$names_array = ($lines);
//simply use the following.
$names_array = file('names.txt', FILE_IGNORE_NEW_LINES); 

阅读file文档:http://www.php.net/manual/en/function.file.php

注意:

结果数组中的每一行都将包括行结束符,除非使用了FILE_IGNORE_NEW_LINES,所以如果不希望出现行结束符,仍然需要使用rtrim()。



/*The text document contains these written names: 
Michael 
Terry 
John 
Phillip*/ 
$lines = file('data.txt'); //Lets say we got an array with these values   //$lines =array('Michael','John','Terry','Phillip');    $i=0;
foreach($lines as $line)   {
$lines[$i] =trim($line);
$i++;   }    
    if (in_array($name, $lines)) {
        echo "exists";
    } else {
        echo 'none';
    } } ?

引用

data.txt

Michael Terry John Phillip

data.txt有空格,所以我们使用trim()来删除它。

最新更新