簡體   English   中英

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);
?>

我不明白為什么當它明顯位於數組中時為什么沒有在數組中找到值“ Sweden”。

這是輸出: https : //pastebin.com/z9rC9Qvk

我還使用了print_r數組,因此您可以看到數組中確實包含“瑞典語”。

希望有人可以幫助:)

您很可能沒有考慮換行符。 以下是使用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);

但這不能解決所有問題。

Windows機器上的countries.txt是嗎? 如果是這樣,則對'\\ n'進行拆分將無法很好地進行,因為每行還有一個'\\ r'。

您的print_r輸出似乎表明這是因為輸出的每一行之間似乎都有一個額外的換行符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM