Php 读取文本文件并将行与完全相同的行进行比较返回false

Php 读取文本文件并将行与完全相同的行进行比较返回false,php,arrays,file,loops,foreach,Php,Arrays,File,Loops,Foreach,我当前的代码: $file = fopen("countries.txt","r"); $array = array(); while(!feof($file)) { $array[] = fgets($file); } fclose($file); 这是我的foreach循环: $str = "test"; foreach ($array as $key => $val) { if ($val == $str) { echo $val;

我当前的代码:

$file = fopen("countries.txt","r");
$array = array();

while(!feof($file)) {
    $array[] = fgets($file);
}

fclose($file);
这是我的foreach循环:

$str = "test";

foreach ($array as $key => $val) {

    if ($val == $str) {
        echo $val;
    } else {
        echo "not found";
    }

}
我想知道为什么它只打印$val,如果它是数组的最后一个值

例如,如果txt文件如下所示,它就可以工作

test1
test2
test3
test
test1
test2
test
test3
但是如果它看起来像这样就不行了

test1
test2
test3
test
test1
test2
test
test3

问题是,每行末尾都有一个新行字符,因此:

test\n !== test
  //^^ See here
这就是为什么它不能像你期望的那样工作

现在怎么解决呢?我可以向您介绍函数:。您可以将文件读入数组,并在每行末尾设置忽略这些新行的标志

因此,将所有这些信息放在一起,您将得到以下代码:

$array = file("countries.txt", FILE_IGNORE_NEW_LINES);
$str = "test";

foreach ($array as $key => $val) {

    if ($val == $str) {
        echo $val;
    } else {
        echo "not found";
    }

}

比较字符串时,应始终使用“==”。

谢谢!我不知道,非常感谢。@user3038431不客气。(顺便说一句:如果您使用旧代码,然后执行:
var\u dump($array);