views:

39

answers:

2

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.

+5  A: 

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.

Pekka
thanks to both of you for this...it's worked!
The Pied Pipes
+1  A: 

Does add *FILE_IGNORE_NEW_LINES* to file() help?

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