2

Why is this code not working?

I have test.txt it contains:

A
B
C

My PHP code is:

$arr = file('test.txt');

if (in_array('A', $arr)) {
   echo 'A is found';
}

Result. nothing. But this following code works fine:

if (in_array('C', $arr)) {
    echo 'C is found';
}

Can someone help me?

2
  • My guess is line breaks. Try example #2 from php.net/trim Commented Jun 30, 2011 at 6:45
  • What does the loaded array look like when you print_r or var_dump it? Commented Jun 30, 2011 at 7:42

1 Answer 1

4

Because file() will not remove the newline symbols from the end of each line, if you don't tell him to do so

$arr = file('test.txt', FILE_IGNORE_NEW_LINES);

or remove it yourself, what will remove any other whitespace from the beginning and end of each line

$array = array_map('trim', file('test.txt'));
Sign up to request clarification or add additional context in comments.

1 Comment

Ok I am a noob, this was so quick and fixed all my issues for now. Thanks

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.