What are the best practices for structuring PHP functions that involve random selection of items with different probabilities?

When structuring PHP functions that involve random selection of items with different probabilities, it is important to properly calculate the cumulative probabilities of each item and use them to determine the range within which the random number falls. This ensures that items with higher probabilities are more likely to be selected.

function weightedRandom($items){
    $totalWeight = array_sum($items);
    $rand = mt_rand(1, $totalWeight);
    
    foreach($items as $key => $weight){
        $rand -= $weight;
        if($rand <= 0){
            return $key;
        }
    }
}

// Example of using the function
$items = [
    'A' => 30,
    'B' => 50,
    'C' => 20
];

$selectedItem = weightedRandom($items);
echo "Selected item: " . $selectedItem;