简体   繁体   中英

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.

Which does perfectly, i can do 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.

This is the output: https://pastebin.com/z9rC9Qvk

I also print_r the array, so you can see that 'Sweden' is indeed in the array.

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 = '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:

$countries_pieces = array_map('trim', $countries_pieces);

But this must not cure all issues.

Is countries.txt from a Windows machine? If so, splitting on '\\n' won't work very well since there's also a '\\r' for every line.

Your print_r output would seem to indicate that since there seems to be an extra newline between every line of output.

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