PHP in_array()找不到数组中的内容


PHP in_array() does not find content that is in an array

我有一个非常简单的脚本,它读取一个txt文件,将内容放入一个数组中。

做得很完美,我可以做print_r($array);并且它输出所有的数据。

我的脚本:

<?php
$file = 'countries.txt';
$countries_output = file_get_contents($file);
$countries_pieces = explode("'n", $countries_output);
if (in_array("Sweden", $countries_pieces)) {
   echo "Sweden was found";
}
else 
{
echo'NOT FOUND';
}
print_r($countries_pieces);
?>

我不明白为什么它在我的数组中找不到"瑞典"的值,而它显然在那里。

这是输出:https://pastebin.com/z9rC9Qvk

我还打印了数组,所以你可以看到"瑞典"确实在数组中。

希望有人能帮忙:)

很可能有一些换行符没有考虑在内。以下是使用file()的更清洁的解决方案,应该适用于您:

$file = 'countries.txt';
$countries_pieces = file($file, FILE_IGNORE_NEW_LINES);
if (in_array("Sweden", $countries_pieces)) {
   echo "Sweden was found";
} else {
    echo'NOT FOUND';
}

如果仍然存在一些问题,一种常见的标准化方法是对trim()值进行归一化,以去除一些遗留问题:

$countries_pieces = array_map('trim', $countries_pieces);

但这决不能解决所有问题。

countries.txt是否来自Windows计算机?如果是这样的话,"''n"上的拆分就不太好了,因为每行都有一个"''r"。

您的print_r输出似乎表明了这一点,因为每一行输出之间似乎都有一条额外的换行符。