简体   繁体   中英

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. 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.

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:

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:

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.

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:

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

Alternatively, apply trim() to each result:

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

The latter will also remove leading and trailing spaces and tabs which may not always be suitable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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