Jump to content

read random line from a text file.


jasonc

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.
Link to comment
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]
Link to comment
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]
Link to comment
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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.