4

I've got a simple script that takes a word from a form and assesses whether it exists in a file (.txt). The txt file has a single word or phrase on each line. There are no \t's or \r in the file.

However, when I submit the form, and POST the first word in the file (e.g. "the"), the following script returns false, when it should return true.

I know this, because when I print out the array $file, I get on screen:

Array
(
    [0] => the
...

So there's something wrong...

$word = $_POST['word']);

// Get a file into an array.
$file = file('master.txt');

if (in_array($word, $file)) {
   echo "true";
}
else {
    echo "false";
}

echo "<pre>";
print_r($file);
echo "</pre>";

Can someone please tell me where I am going wrong here, since the array being returned by the file() appears to be clean, and the POSTed word ("the") is the first value in the file() array. I have checked to ensure that the POST data is in fact submitting properly too.

TIA.

1
  • 1
    Is "the" on a separate line in the file? The file() function returns an array with an element corresponding to each line in the file. Commented Jul 24, 2010 at 22:29

2 Answers 2

6

When you run file(), the resulting array will contain the line breaks:

Note: Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.

The easiest way is probably using the FILE_IGNORE_NEW_LINES parameter.

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

Comments

3

Does add FILE_IGNORE_NEW_LINES to file() help?

$file = file('master.txt', FILE_IGNORE_NEW_LINES);

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.