Hey, I hope you can help!! I have a text file (as below), and id like to lines of the text file completely at random. I.e. it could show, line 6, line 9, line 1, line 17 etc etc TextFile Example: Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 Line 11 Line 12 Line 13 Line 14 Line 15 Line 16 Line 17 Line 18 Line 19 Line 20 i.e. if it was mysql, i could use the following: SELECT * FROM table ORDER BY RAND() LIMIT 10 Hope you can help! Chris
Hello Chris Well, try this... $file = "path_file.txt"; $rows = file($file); //random lines. shuffle($rows); foreach($rows as $r) { echo $r . "<BR>"; } PHP:
Oh yeah $file = "path_file.txt"; $rows = file($file); $i = 0; //random lines. shuffle($rows); foreach($rows as $r){ if($i == $limit){ break(1); } echo $r . "<BR>"; } PHP:
Oh yeah <? $file = "your_file.txt"; $rows = file($file); //Choose a limit of rows. $limit = 10; $i = 0; //random lines. shuffle($rows); foreach($rows as $r){ if($i == $limit){ break(1); } echo $r . "<BR>"; $i++; } ?> PHP: or, using for statement... <? $file = "your_file.txt"; $rows = file($file); //Choose a limit of rows. $limit = 10; //random lines. shuffle($rows); for($x = 0; $x < $limit; $x++) { echo $rows[$x] . "<BR>"; } ?> PHP:
Or using array_slice: $file = "path_file.txt"; $rows = file($file); //random lines. shuffle($rows); // get only the first 10 $output = array_slice($rows, 0, 10); foreach($output as $r) { echo $r . "<BR>"; } PHP: http://php.net/array_slice
More easiest will be $lines = file("yourfile.txt"); $rand = rand(1, count($lines)); print $lines[$rand]; PHP: Not tested, but shud work