1

I am putting the contents of an text file into an array via the file() command. When I try and search the array for a specific value it does not seem to return any value but when I look at the contents of the array the value I am searching for is there.

Code used for putting text into array:

    $usernameFileHandle = fopen("passStuff/usernames.txt", "r+");
    $usernameFileContent = file("passStuff/usernames.txt");
    fclose($usernameFileHandle);

Code for searching the array

$inFileUsernameKey = array_search($username, $usernameFileContent);

Usernames.txt contains

Noah
Bob
Admin

And so does the $usernameFileContent Array. Why is array_search not working and is there a better way to do this. Please excuse my PHP noob-ness, thanks in advance.

2 Answers 2

2

Because file():

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached

To prove this try the following:

var_dump(array_search('Bob
', $usernameFileContent));

You could use array_map() and trim() to correct the behavior of file(). Or, alternatively, use file_get_contents() and explode().

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

Comments

1

To quote the docs:

Each element of the array corresponds to a line in the file, with the newline still attached.

That means that when you're doing the search, you're searching for "Noah" in an array that contains "Noah\n" - which doesn't match.

To fix this, you should run trim() on each element of your array before you do the search.

You can do that using array_map() like this:

$usernameFileContent = array_map($usernameFileContent, 'trim');

Note, too, that the file() function operates directly on the provided filename, and does not need a file handle. That means you to do not need to use fopen() or fclose() - You can remove those two lines entirely.

So your final code could look like this:

$usernameFileContent = array_map(file('passStuff/usernames.txt'), 'trim');
$inFileUsernameKey = array_search($username, $usernameFileContent);

1 Comment

If you don't specify strict mode, shouldn't it return the key for "Noah\n" even if the needle is "Noah"?

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.