0

I would like to display the 'words' in alphabetical order, but all of the examples of solutions that I have come across, are not working for me.

I have tried using the implode() and explode() functions, using the file() function, and then using the sort() function.

Any help is very much appreciated, thank you!

<!DOCTYPE html>
<html>
  <head>
    <title>words list</title>
  </head>
  <body>
    <h1>Word List</h1> 
    <?php
      @$fp = fopen("words.txt", 'rb');
      flock($fp, LOCK_SH); // lock file for reading



      while (!feof($fp)) {
         $words= fgets($fp);
     explode($words, "\n");
         file($words);
         sort($words);

         echo htmlspecialchars($words)."<br />";
      }
      flock($fp, LOCK_UN); // release read lock

      fclose($fp); 
    ?>
  </body>
</html>
3
  • It's better if you provide the sample content of the file. Commented Apr 17, 2019 at 1:59
  • I'm trying to make a glossary. Every line of the txt file is another word. Mostly just test words so far. Commented Apr 17, 2019 at 2:22
  • 1
    have you considered the many many advantages of a database over a flat file? Commented Apr 17, 2019 at 3:21

2 Answers 2

3
<!DOCTYPE html>
<html>
  <head>
    <title>words list</title>
  </head>
  <body>
    <h1>Word List</h1> 
    <?php
    $lines = file("words.txt");
    print_r($lines);
    natsort($lines); // this will sort lines in your file
    print_r($lines);
    // This was optional here you can overwrite existing file or can create new file
    file_put_contents("newtime.txt", implode("\n", $lines)); 
    ?>
  </body>
</html>

I checked and It works for me ! ! !

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

3 Comments

Thank you! this is exactly what I needed!
do you know of a way I can list just the sorted words array? I have tried using for loops but they do not work. Thank you for your time!
From my assumption you are asking for list sorted array right?, foreach ($lines as $key => $value) { echo $value; }
0

Sorry; I misread your question. You need to put the values into an array in order to sort it.

> $i = 0;
>      while (!feof($fp)) {
>              $words[$i] = fgets($fp);
>              
>              $i++;
>           }
>      sort($words);
>     echo htmlspecialchars($words)."<br />";

1 Comment

Your way is less efficient, turning it into a string and then making it into an array. You're also just overwriting the value $words with the last line of code. Then, you turn your string array into one big array with file, so there's nothing to sort.

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.