phparraysrandomprobabilityweighted

Ensure specific probability when randomly accessing array values


I using the rand from php. That below script is working perfect, But My question is to give the priority for the one value in array(Show multi times). For example 100 times it randomly show the value, Is it possible to make the 0 to 99 times it echo the dofollow and 1 time it show nofollow using rand

$input_nofollow = array("nofollow", "dofollow");
$random = rand(0, 1);
echo $input_nofollow[$random];

Solution

  • $random = rand(0, 100);
    $selected_key = 0;
    if($random < 90) $selected_key = 1;
    else $selected_key = 0;
    
    echo $input_nofollow[$selected_key];
    

    This give you a ~90% chance to get the index 1.