1

I've been trying for two days to create an array from a text file list, shuffle it, then rewrite the text file using file_put_contents.

I've succeeded in doing so BUT when I run the script more than once it creates multiple and random spaces between each item.

I've tried many different ideas but no joy yet.

Below is my code.

    <?php

         // create array from text file
         $array = file('list.txt');

         // shuffle the array
         shuffle ($array);

         // overwrite original with new shuffled text file
         file_put_contents('list.txt', implode(PHP_EOL, $array));

         ?> 

1 Answers1

0

It seem like you may have extra line returns. These would also be part of the array and subject to random shuffling. IF you want to remove them you can do this

 $array = array_filter(array_map('trim', $array));

The array map trim just runs trim() on every item in the array, this will help get rid of lines that have spaces in them instead of being strictly empty. Trim simply removes any whitespace from the front and back of a string, in the case that the whole line is whitespace then all the whitespace is removed leaving an empty string '' for that line.

The array filter will remove any lines that evaluate out to 0 in php this is '' 0 false null and maybe a few other things.

So by combining them we can easily filter out any lines that contain only whitespace or are empty.

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • This was VERY helpful and I know for experienced programmers it's probably pathetic, but thanks to people like ArtisticPhoenix us complete newbies can get a helping hand after working on a problem for days with no progress. Thanks again! Unfortunately my vote for answer is not visible because of my account status at the time. –  Nov 11 '17 at 17:00