Jeff Tidwell
Jeff Tidwell

Reputation: 75

Choose between two items based upon a given percentage

I need to display one of two items in an array based up on a 40/60% ratio. So, 40% of the time, item one displays and 60% of the time, item two displays.

I now have the following code that will just randomly choose between the two, but need a way to add the percentage weight to it.

$items = array("item1","item2");
$result = array_rand($items, 1);

echo $items[$result];

Any help would be appreciated. Thanks!

Upvotes: 4

Views: 1414

Answers (6)

aaa
aaa

Reputation: 786

Something like that should do the trick

$result = $items[ rand(1, 100) > 40 ? 1 : 0 ];

Upvotes: 8

h4cky
h4cky

Reputation: 894

What about ?

$rand = mt_rand(1, 10);
echo (($rand > 4) ? 'item2' : 'item1');

Upvotes: 1

ekholm
ekholm

Reputation: 2573

$index = rand(1,10) <= 4 ? 0 : 1;
echo $items[$index];

Upvotes: 0

Ry-
Ry-

Reputation: 225054

if(rand(0, 100) <= 40) {
    # Item one
} else {
    # Item two
}

Upvotes: 3

enricog
enricog

Reputation: 4273

Just use normal rand method:

if (rand(1,10) <= 4) {
    $result = $items[0];
} else {
    $result = $items[1];
}

Upvotes: 3

Shehzad Bilal
Shehzad Bilal

Reputation: 2523

$val = rand(1,100);
if($val <= 40)
  return $items[0]; 
else 
  return $items[1];

Upvotes: 4

Related Questions