Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in_array returning false when should return true

Tags:

arrays

php

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.

like image 487
The Pied Pipes Avatar asked Jan 21 '23 17:01

The Pied Pipes


2 Answers

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.

like image 86
Pekka Avatar answered Jan 24 '23 05:01

Pekka


Does add FILE_IGNORE_NEW_LINES to file() help?

$file = file('master.txt', FILE_IGNORE_NEW_LINES);
like image 34
srparish Avatar answered Jan 24 '23 05:01

srparish