[英]PHP in_array() does not find content that is in an array
i have a very simple script that reads out a txt file, puts the content in an array. 我有一个非常简单的脚本,可以读取txt文件,并将内容放入数组中。
Which does perfectly, i can do print_r($array)
; 哪个做得很好,我可以做
print_r($array)
; and it outputs all the data. 并输出所有数据。
My script: 我的剧本:
<?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);
?>
I don't understand why it doesn't find the value 'Sweden' in my array, when it clearly is in there. 我不明白为什么当它明显位于数组中时为什么没有在数组中找到值“ Sweden”。
This is the output: https://pastebin.com/z9rC9Qvk 这是输出: https : //pastebin.com/z9rC9Qvk
I also print_r the array, so you can see that 'Sweden' is indeed in the array. 我还使用了print_r数组,因此您可以看到数组中确实包含“瑞典语”。
Hope someone can help :) 希望有人可以帮助:)
There is most likely new line characters that you're not taking into account. 您很可能没有考虑换行符。 The following is a cleaner solution using
file()
and should work for you: 以下是使用
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';
}
If there are still some issues, a common normalization is to trim()
values to remove some left-overs: 如果仍然存在一些问题,通常的归一化方法是
trim()
值以除去一些剩余的东西:
$countries_pieces = array_map('trim', $countries_pieces);
But this must not cure all issues. 但这不能解决所有问题。
Is countries.txt from a Windows machine? Windows机器上的countries.txt是吗? If so, splitting on '\\n' won't work very well since there's also a '\\r' for every line.
如果是这样,则对'\\ n'进行拆分将无法很好地进行,因为每行还有一个'\\ r'。
Your print_r output would seem to indicate that since there seems to be an extra newline between every line of output. 您的print_r输出似乎表明这是因为输出的每一行之间似乎都有一个额外的换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.