How to use the mt_rand function, so it wont repeat?

Hi all

I am using a mt_rand function to set different styles each time a user clicks on my page, how can i make sure it will not repeat the same style after a refresh?

<?php
#############################################################################
function SetStyle(){
 
    $style[] = "css/n1.css";
	$style[] = "css/n2.css";
	$style[] = "css/n3.css";
	$style[] = "css/n4.css";
	$style[] = "css/n5.css";
	$style[] = "css/n6.css";
	$number = mt_rand(0,5);
	$stylesheet = $style[$number];
 
 return $stylesheet;
}
?>

Open in new window

PeterdeBAsked:
Who is Participating?
 
Cornelia YoderConnect With a Mentor ArtistCommented:
Unless you save the previous values and check against them, you cannot guarantee this.  Random is random, and occasionally a die rolls the same number twice in a row.
0
 
WerrockCommented:
You could save the old value in a session and always run the rand function while it returns the same value as saved in the session.
0
 
ddrudikCommented:
Possibly not the best application of a random function (seems like you could just cycle through them one by one), with the random function as applied on average you expect 1 in 6 numbers to be a duplicate of the previous number, consider this code to illustrate:
<pre>
<?php
$number=0;
$oldnumber=0;
$dup=0;
for($i = 0; $i < 1000000; $i++) {
	$number = mt_rand(0,5);
	if($oldnumber==$number){
		$dup++;
	}
	$oldnumber=$number;
}
echo "There were $dup duplicates out of 1,000,000.";
?>
 
Output:
There were 166103 duplicates out of 1,000,000.

Open in new window

0
 
PeterdeBAuthor Commented:
thank you, but will using a different function fix this? Well i will post a new question, since this question is answered by the first expert, again thanks all
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.