簡體   English   中英

從函數返回數組時,in_array函數無法正常工作

[英]in_array function doesn't work well when returning an array from a function

我有一個打開遠程文件以使用cURL庫獲取其內容的功能。 然后該函數返回一個包含文件內容的數組。

然后,當使用in_array函數檢查該特定值是否存在於數組中時,即使該值確實存在,它也始終顯示該值不存在。

這是代碼,以及遠程文件的內容。

function getCountry($file) {
    $fop = curl_init($file);
    curl_setopt($fop, CURLOPT_HEADER, 0);
    curl_setopt($fop, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($fop);
    curl_close($fop);
    $fcontent = explode("\n", $result);
    return $fcontent;
}

$file = "http://localhost/countries.txt";
$countries = getCountry($file);

if (in_array('italy', $countries)) {
    echo "Exists";
} else {
    echo "Not exists";
}

在遠程文件countries.txt的內容中,一行中的每個句子或單詞都像這樣:

spain
italy
norway
canada
france

如前所述, 它始終表明該值不存在,即使確實存在。

我非常確定您的源文件中包含稀疏字符,例如回車符。 getCountry調用之后嘗試以下操作:

foreach($countries as &$country) {
  echo "'$country' (".strlen($country).")<br>";
  $country = trim($country);
}

如果它給“意大利” strlen 6分的驚喜,並解決此問題,我不會感到驚訝。

正確的解決方法是在解析后立即清理內容:

$fcontent = array_map('trim', explode("\n", $result));

如果不確定文件中是否存在CRLF,可以使用preg_split()代替explode() ,如下所示:

return preg_split('/\r?\n/', $result);

或者,對每個結果應用trim()

return array_map('trim', explode("\n", $result));

后者還將刪除可能並不總是合適的前導和尾隨空格和制表符。

暫無
暫無

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

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