Jump to content

[SOLVED] how to add a randomizer


purplenewt

Recommended Posts

hi all,

 

I am working on a project that must use only php (no database unfortunatly).

It has to generate a selected number of random quotes but they must not repeat themselves.

 

the quotes I have put into an array like so:

 

<ul>
     1.<?php
	echo ($quote[0]);
	?>
</ul>
<hr />
<ul>
	2.<?php
		echo ($quote[1]);
	?>
        </ul>
<hr />
<ul>
        3.<?php
	echo ($quote[2]);
	?>
</ul>
<hr />
<ul>
	4.<?php
	echo ($quote[3]);
	?>
</ul>
<hr />
and so on

 

I know i need need to replace the numbers within the  [] with a random number and I have a way to generate random numbers that do not repeat. Like so.

 

<?php
function rand_group($num) {
   $ary = range(1,50);
   shuffle($ary);
   return array_slice($ary, 0, $num);
}

echo implode(', ',rand_group(5));
?>

 

I just dont understand how i can get the numbers generated from this code into the [] to make sure i get no repeating quotes.

 

I'm still very new at php but sometimes seems like i'm getting there just for hiccups like this to stump me totally.

 

Any help would be greatly appreciated.

 

Thanks

 

 

Purplenewt

Link to comment
https://forums.phpfreaks.com/topic/135048-solved-how-to-add-a-randomizer/
Share on other sites

Assuming your quotes are in an array called $quotes

 

<?php

  function random_quotes($quotes)  {
  
    $q = array();
  
      for($count = 0; $count <= 2; $count += 1) {
        $num = rand(0, count($quotes)-1);
        
          while(in_array($num, $q)) $num = rand(0, count($quotes)-1);
            array_push($q, $num);
      }
    return $q;    
  }

?>

 

Without testing much, that should return an array with three random keys. You can then display your quotes by using a foreach loop.

 

<?php

  $q = random_quotes($quotes);
  $i = 1;

  foreach ($q as $key)  {
    echo'<ul>'.$i.'. '.$quotes[$key].'</ul>';
    $i++;
  }

?>

I had to do something like this a long time ago (years):

 

<?php
$quotes = file('quotes.txt');
$rand = rand(0, count($quotes) -1);
echo $quotes[$rand];

 

quotes.txt:

This is a quote! -Cite
This is another quote! -Cite
This is yet another quote! -Cite
Wow! More quotes! -Cite

 

Obviously, the less you have as far as number of quotes, the less random it's going to be.

 

If you are belching out a number of quotes and they must be unique, you'll need to keep track of keys that have been echo'd and make sure they aren't pushed out again.

Archived

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

×
×
  • 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.