Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 406
Jeff Tidwell Avatar asked Dec 01 '22 23:12

Jeff Tidwell


2 Answers

Something like that should do the trick

$result = $items[ rand(1, 100) > 40 ? 1 : 0 ];
like image 102
aaa Avatar answered Feb 12 '23 21:02

aaa


$val = rand(1,100);
if($val <= 40)
  return $items[0]; 
else 
  return $items[1];
like image 27
Shehzad Bilal Avatar answered Feb 12 '23 21:02

Shehzad Bilal