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

Mr.*_*oon 1 php arrays

我有一个非常简单的脚本,它读出一个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);
?>
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它在我的阵列中找不到"瑞典"的值,当它显然在那里时.

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

我也print_r数组,所以你可以看到'瑞典'确实在数组中.

希望有人可以帮忙:)

Tim*_*per 9

您很可能没有考虑新的线条字符.以下是一个更清洁的解决方案使用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';
}
Run Code Online (Sandbox Code Playgroud)

如果仍然存在一些问题,则常见的规范化是trim()删除一些剩余的值:

$countries_pieces = array_map('trim', $countries_pieces);
Run Code Online (Sandbox Code Playgroud)

但这绝不能解决所有问题.