PDA

View Full Version : Random echo: PHP



Jahova
30-07-2010, 03:56 PM
Right. I'm useless with PHP so I'll explain what I would like..

Say I've got loads of different lines of song lyrics. I want to put these lyrics into a php script which would chose a random one each time the page is loaded / refreshed and echoed to the page.

Should be simple, I used to know how to do this but my old age has got the better of me (lol, jk).

Thanks, +REP to those who assist.

Luke
30-07-2010, 04:07 PM
Put all the song lyrics on lines in notepad, save as TXT file



<?php
$quotes = "lyrics.txt";
$quotes = file($quotes);
srand((double)microtime() * 1000000);
$ranNum = rand(0, count($quotes)-1);
echo ($quotes[$ranNum]);
?>

Jahova
30-07-2010, 06:16 PM
Thank you. Perfect :D

REP / thread closed.

Blob
30-07-2010, 06:21 PM
Simpler way



<?php
$array = array("LINE1", "LINE2", "LINE3","etc..");

echo $array[ rand( 0, count( $array ) - 1 ) ];
?>


should work, untested

Dentafrice
30-07-2010, 06:23 PM
Simpler way



<?php
$array = array("LINE1", "LINE2", "LINE3","etc..");

echo $array[ rand( 0, count( $array ) - 1 ) ];
?>


should work, untested

Then he has to put all those lyrics into that array... which is time consuming; as well as pointless when he could just separate each line from the text file... it's so much easier to put new lines then quotes and commas round each one.

Jahova
30-07-2010, 06:24 PM
Thanks both. Any cleaner way to do it using the first method? :)

Dentafrice
30-07-2010, 06:25 PM
Thanks both. Any cleaner way to do it using the first method? :)

You don't have to seed the RNG if you're using above PHP 4.2 I think?

Jahova
30-07-2010, 06:29 PM
You don't have to seed the RNG if you're using above PHP 4.2 I think?

English would be brilliant :D Maybe an example? Thanks

Dentafrice
30-07-2010, 06:33 PM
<?php

function random_quote($data) {
$random_number = rand(0, count($data) - 1);
return $data[$random_number];
}

$filename = "lyrics.txt"; // path to lyrics file
$data = file($filename); // gets each line of a file and puts it into an array.

echo random_quote($data);
echo random_quote($data);
?>


That lets you display a random quote each time you call random_quote.

Jahova
30-07-2010, 06:37 PM
Thanks for your time, all. +REPPED

Want to hide these adverts? Register an account for free!