Jump to content

Archived

This topic is now archived and is closed to further replies.

jasonc

read random line from a text file.

Recommended Posts

I have a large file with a list of songs, i wish to chose at random 5 of these to be shown on my web page.

the problem i have is reading this file to get the info from it.

i have the php script that randomise 5 numbers all i need is to know how to extract the lets say

the 5, 17, 26, 55, 105 and er 300 th lines from a text (tracks.txt) file.

I known in the past that scripts can write a file but how can i read a line from one?

also been told be a friend that when i do this i also need to be sure that the file can be read many time at the same time.

I was going to use my database but decided against that as i have had problems in the past with them.
also adding the data to it would take ages too.

thank you in advance for your help.

Share this post


Link to post
Share on other sites
This is what I came up with. There are a several solutions.

[code]
*** Came up with a different solution than before...
<?
$file = file('/etc/passwd');
shuffle($file);

for($i=0;$i<5;$i++) printf("%s\n", trim($file[$i]));
?>
[/code]

Share this post


Link to post
Share on other sites
[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]I was going to use my database ... adding the data to it would take ages too.[/quote]

why, if you already have the data in a text file?


Try

[code]$songs = file('songlist.txt');

$rand_titles = array_rand($songs, 5);

foreach ($rand_titles as $k) {
          echo $songs[$k], '<br />';
}[/code]

Share this post


Link to post
Share on other sites
thank you very much for your help, this worked a treat. i now have a new command to play around with and get to know.

J


[!--quoteo(post=366218:date=Apr 18 2006, 11:22 PM:name=Barand)--][div class=\'quotetop\']QUOTE(Barand @ Apr 18 2006, 11:22 PM) [snapback]366218[/snapback][/div][div class=\'quotemain\'][!--quotec--]
why, if you already have the data in a text file?
Try

[code]$songs = file('songlist.txt');

$rand_titles = array_rand($songs, 5);

foreach ($rand_titles as $k) {
          echo $songs[$k], '<br />';
}[/code]
[/quote]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.