简体   繁体   English

从函数返回数组时,in_array函数无法正常工作

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

I have a function which opens a remote file to get its content with the cURL library. 我有一个打开远程文件以使用cURL库获取其内容的功能。 Then the function returns an array containing the content of the file. 然后该函数返回一个包含文件内容的数组。

Then, when it checks whether that specific value exists in the array by using the in_array function, it always shows that the value doesn't exist, even though it does. 然后,当使用in_array函数检查该特定值是否存在于数组中时,即使该值确实存在,它也始终显示该值不存在。

Here's the code and also the content of remote file. 这是代码,以及远程文件的内容。

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";
}

In the content of the remote file countries.txt , every sentence or word in a line is like this: 在远程文件countries.txt的内容中,一行中的每个句子或单词都像这样:

spain
italy
norway
canada
france

As I mentioned previously, it always shows that the value doesn't exist, even though it does. 如前所述, 它始终表明该值不存在,即使确实存在。

I'm mighty sure you've got sparse characters such as carriage returns in your source file. 我非常确定您的源文件中包含稀疏字符,例如回车符。 Try this after the getCountry call: getCountry调用之后尝试以下操作:

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

Wouldn't surprise me if it gave a strlen of 6 for 'italy', and fix the problem along the way. 如果它给“意大利” strlen 6分的惊喜,并解决此问题,我不会感到惊讶。

The proper fix would be to clean up the content right after parsing: 正确的解决方法是在解析后立即清理内容:

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

If you're not sure whether there will be CRLF in the file, instead of explode() you can use preg_split() like this: 如果不确定文件中是否存在CRLF,可以使用preg_split()代替explode() ,如下所示:

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

Alternatively, apply trim() to each result: 或者,对每个结果应用trim()

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

The latter will also remove leading and trailing spaces and tabs which may not always be suitable. 后者还将删除可能并不总是合适的前导和尾随空格和制表符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM