Luke Bream
Luke Bream

Reputation: 855

I'm creating a random array in PHP and my code doesnt seem to output a truly random answer

I want to construct an array of 3 offers that output in a random order. I have the following code and whilst it does output 3 random offers it doesn't appear to be random. The first value in the generated array always seems to be from the 1st 2 records in my offers table. The offers table only has 5 records in it (I dont know if this is affecting things).

$arrayOfferCount = $offerCount-1;
$displayThisManyOffers = 3;

$range = range(0, $arrayOfferCount);
$vals = array_rand($range, $displayThisManyOffers);`

Any help or advice would be appreciated.

Upvotes: 0

Views: 127

Answers (4)

Julien Schmidt
Julien Schmidt

Reputation: 1060

array_rand seems not to work properly sometimes (see PHP-Manual comments).

Workaround: Get the array size and pick a random index using the function mt_rand

Upvotes: 0

ceejayoz
ceejayoz

Reputation: 179994

Working fine here. Benchmark it over lots of runs instead of just gut feeling... here it is for 1,000 tries:

<?php

$offerCount = 5;
$arrayOfferCount = $offerCount-1;
$displayThisManyOffers = 3;

$range = range(0, $arrayOfferCount);

for($i = 0; $i < 1000; $i++) {
    $vals = array_rand($range, $displayThisManyOffers);

    foreach($vals as $val) {
        $counts[$val]++;
    }
}

sort($counts);
print_r($counts);

Generates:

Array
(
    [0] => 583
    [1] => 591
    [2] => 591
    [3] => 610
    [4] => 625
)

Upvotes: 2

Xeoncross
Xeoncross

Reputation: 57184

I know that mt_rand() is much better PRNG.

However, in your case you need to let the database select them for you

SELECT * FROM ads ORDER BY RAND() LIMIT 0, 3

Upvotes: 1

nschomer
nschomer

Reputation: 35

It is probably randomly picking which to display, but displaying them in the same order they appear in your array. If you do it enough times (~20) you should get the third one to show up once if this is the case (chances of choosing exactly the last 3 out of 5 would be 1 in 5*4, so around every 20th one you'll see the third option appear).

Upvotes: 0

Related Questions