Choose between two items based on a given percentage

I need to display one of two elements in an array based on a 40/60% ratio. Thus, 40% of the time, the first item is displayed and 60% of the time, item 2 is displayed.

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

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

Any help would be greatly appreciated. Thanks!

+4
source share
6 answers

Something like this should do the trick

 $result = $items[ rand(1, 100) > 40 ? 1 : 0 ]; 
+9
source
 $val = rand(1,100); if($val <= 40) return $items[0]; else return $items[1]; 
+4
source

Just use the regular rand method:

 if (rand(1,10) <= 4) { $result = $items[0]; } else { $result = $items[1]; } 
+3
source
 if(rand(0, 100) <= 40) { # Item one } else { # Item two } 
+3
source

What about?

 $rand = mt_rand(1, 10); echo (($rand > 4) ? 'item2' : 'item1'); 
+1
source
 $index = rand(1,10) <= 4 ? 0 : 1; echo $items[$index]; 
0
source

All Articles