1

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 :)

0

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yup - there's probably still a \r, or some other weirdness there.
@Godius: Remember to mark the question as answered if the answer solved your issue.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.