Jump to content


Random Text


4 replies to this topic

#1 Bouzy210

    Jedi In Training

  • Members
  • PipPip
  • 434 posts
  • Gender:Male

Posted 17 July 2007 - 08:51 PM

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.)

#2 Demonslay

    P2L Jedi

  • Members
  • PipPipPip
  • 970 posts
  • Gender:Male
  • Location:A strange world where water falls out of the sky... for no reason.
  • Interests:Graphic Design, Coding, Splinter Cell, Cats

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 Bouzy210

    Jedi In Training

  • Members
  • PipPip
  • 434 posts
  • Gender:Male

Posted 17 July 2007 - 11:03 PM

Thanks I will try that in the morning.

#4 Demonslay

    P2L Jedi

  • Members
  • PipPipPip
  • 970 posts
  • Gender:Male
  • Location:A strange world where water falls out of the sky... for no reason.
  • Interests:Graphic Design, Coding, Splinter Cell, Cats

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 Ali Imran

    Young Padawan

  • Members
  • Pip
  • 7 posts

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
$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