开发者

in_array returning false when should return true

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 PO开发者_开发问答ST data is in fact submitting properly too.

TIA.


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.


Does add FILE_IGNORE_NEW_LINES to file() help?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜