Bilge Posted May 3, 2020 Share Posted May 3, 2020 In the following code: echo $text[2] returns the word at that index but echo $key returns a blank. Can someone explain why is array-search not working in this indexed array? It does work when I test it with a key => value type array. <?php $myfile = fopen("test.txt", "r") or die("Unable to open file!"); while(!feof($myfile)) { $text[] = fgets($myfile); } fclose($myfile); $word = $_POST['word']; $key = array_search($word, $text); echo $key ?> Quote Link to comment Share on other sites More sharing options...
Barand Posted May 3, 2020 Share Posted May 3, 2020 Does a var_dump() of $word and $text[2] reveal any differences? Quote Link to comment Share on other sites More sharing options...
Bilge Posted May 3, 2020 Author Share Posted May 3, 2020 Thank you for your response. Yes var_dump does reveal a difference. print_r(var_dump($text[2])) produces: string(8) "charlie with the second " on a new line print_r(var_dump($word)) produces: string(7) "charlie" Quote Link to comment Share on other sites More sharing options...
Barand Posted May 3, 2020 Share Posted May 3, 2020 8 hours ago, Bilge said: Can someone explain why is array-search not working in this indexed array? The var_dump() output has now shown you why - the values are not the same. You search for "charlie" but array contains "charlie\n" Quote Link to comment Share on other sites More sharing options...
Bilge Posted May 3, 2020 Author Share Posted May 3, 2020 Yes, and trim() has sorted it out. Thank you for your help Quote Link to comment Share on other sites More sharing options...
Barand Posted May 3, 2020 Share Posted May 3, 2020 (edited) You could replace $myfile = fopen("test.txt", "r") or die("Unable to open file!"); while(!feof($myfile)) { $text[] = fgets($myfile); } fclose($myfile); with $text = file('test.txt', FILE_IGNORE_NEW_LINES); Edited May 3, 2020 by Barand Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.