recoup8063
recoup8063

Reputation: 4280

php array_search not returning values

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.

Upvotes: 1

Views: 590

Answers (2)

jcsanyi
jcsanyi

Reputation: 8174

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);

Upvotes: 1

Jason McCreary
Jason McCreary

Reputation: 72991

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().

Upvotes: 2

Related Questions