Reputation: 75
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
Reputation: 786
Something like that should do the trick
$result = $items[ rand(1, 100) > 40 ? 1 : 0 ];
Upvotes: 8
Reputation: 894
What about ?
$rand = mt_rand(1, 10);
echo (($rand > 4) ? 'item2' : 'item1');
Upvotes: 1
Reputation: 4273
Just use normal rand
method:
if (rand(1,10) <= 4) {
$result = $items[0];
} else {
$result = $items[1];
}
Upvotes: 3
Reputation: 2523
$val = rand(1,100);
if($val <= 40)
return $items[0];
else
return $items[1];
Upvotes: 4