So for my website I decided to intigrate some php. What I want to do is display random text so every time a page is refresed a different paragraph is displayed in a certain spot. For this all I can figure is I need the $i = rand or something like that and an array with text strings in it. Could someone describe what I need to do here. I am a bit unclear about how to make the random funtion work with text strings and stuff.. Some sample code might also help.
(I have looked on P2life and the only tutorials I can find are about displaying random images.)
Random Text
Started by Bouzy210, Jul 17 2007 08:51 PM
4 replies to this topic
#1
Posted 17 July 2007 - 08:51 PM
#2
Posted 17 July 2007 - 10:20 PM
The concept is the exact same, only you just place text instead of images.
$text = array(); $text[0] = 'Heres a random sentence.'; $text[1] = 'Les lapins viennent!'; $text[2] = 'Foobarglarz!'; echo $text[rand(0, count($text))];
#3
Posted 17 July 2007 - 11:03 PM
Thanks I will try that in the morning.
#4
Posted 18 July 2007 - 12:58 PM
Opps, small error in my code. Forgot to subtract one from the max random number in order to compensate for array index numbering.
$text = array(); $text[0] = 'Heres a random sentence.'; $text[1] = 'Les lapins viennent!'; $text[2] = 'Foobarglarz!'; echo $text[rand(0, count($text) - 1)];
#5
Posted 22 July 2007 - 05:51 PM
Nice code Demonslay. Few cents from me.
You can also maintain different strings in a plain text file and load them easily.
for example your text file has 4 lines and each line is a different text.
//Load entire file in array
//Do some clean up, discard empty lines etc, and trim
//Now pick random one
This way it becomes easy for you to update text file rather than getting into code again and again.
regards
You can also maintain different strings in a plain text file and load them easily.
for example your text file has 4 lines and each line is a different text.
//Load entire file in array
$text = file("mystrings.txt");
//Do some clean up, discard empty lines etc, and trim
foreach($text as $k => $v) {
$v = str_replace("\r",str_replace("\n",trim($v)));
if($v == '')
unset($text[$k]);
else
$text[$k] = $v;
}
//Now pick random one
$random_text = $text[rand(0,count($text)-1)]; print "$random_text <br/>";
This way it becomes easy for you to update text file rather than getting into code again and again.
regards
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users
