VampireNews
VampireNews

Reputation: 45

If variable equals variable change a variable

I was wondering how I can make it to where 3 variables never have the same number using rand()?

<?php
$myAd[1] = '<a href="http://www.pegor.com">Free PHP Tutorials</a>';
$myAd[2] = '<a href="http://www.lifestinks.info">Fast Facebook Proxy</a>';
$myAd[3] = '<a href="http://www.mozilla.org">Fastest and Secure Web Browser</a>';

$adId = rand(1,count($myAd));
$adId2 = rand(1,count($myAd));
$adId3 = rand(1,count($myAd));
if ($adId === $adId2) { $adId = ($adId2 - 1) }
if ($adId === $adId3) { $adId = ($adId3 - 1) }
if ($adId2 === $adId3) { $adId2 = ($adId3 - 1) }

echo $myAd[$adId];
echo '<br>';
echo $myAd[$adId2];
echo '<br>';
echo $myAd[$adId3];
?>

In a nutshell what I would like to accomplish is my site displaying 3 products on the left column. Every time a user refreshes they change. The issue I keep running into is 2 of the variables that the random number generates are the same. How can I make it to where they always land on different numbers so 3 different products are displayed at a time instead of 2 the same and 1 different? Note: I will be adding more items to the array, that is just a test script until I figure it out.

Upvotes: 1

Views: 298

Answers (3)

BlitZ
BlitZ

Reputation: 12168

Try shuffle() and array_slice():

$myAd = array();
$myAd[1] = '<a href="http://www.pegor.com">Free PHP Tutorials</a>';
$myAd[2] = '<a href="http://www.lifestinks.info">Fast Facebook Proxy</a>';
$myAd[3] = '<a href="http://www.mozilla.org">Fastest and Secure Web Browser</a>';
// more of...

shuffle($myAd);

$myAd = array_slice($myAd, 0, 3);

foreach($myAd as $value){
    echo $value, '<br/>', PHP_EOL;
}
?>

Upvotes: 1

user1088172
user1088172

Reputation:

Example how to compare two but you can improve of basically you need most

$rnd1 = rand(0,9);
do {
  $rnd2 = rand(0,9);
} while ($rnd1 == $rnd2);

Firstly you need to put your random variable to one variable and then do while where the random 1 equals to random 2 you can do more complex from what you need.

GBU

Upvotes: 0

sectus
sectus

Reputation: 15464

$adId = rand(1, count($myAd));
do
    { $adId2 = rand(1, count($myAd)); }
while ($adId2 == $adId);

do
    { $adId3 = rand(1, count($myAd)); }
while ($adId3 == $adId || $adId3 == $adId);

But better to use shuffle() and array_slice().

Upvotes: 1

Related Questions