This article mainly introduces the method of obtaining random combinations from specified numbers in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.
For example: Given the number 100, you need to randomly obtain 3 combinations that make up this number, such as 70, 20, 10
The code is as follows:
<?php /** * 获取指定数字的随机数字组合 * @param Int $var 数字 * @param Int $num 组合这个数字的数量 * @return Array */ function getNumGroups($var, $num){ // 数量不正确 if($var<$num){ return array(); } $total = 0; $result = array(); for($i=1; $i<$num; $i++){ $tmp = mt_rand(1, $var-($num-$i)-$total); $total += $tmp; $result[] = $tmp; } $result[] = $var-$total; return $result; } // demo $result = getNumGroups(100, 3); print_r($result); ?>
##Output:
Array ( [0] => 42 [1] => 25 [2] => 33 )
Php, MySQL environment configuration
PHPFunction curl request-fetch page/interface test
The above is the detailed content of php method to get random combinations from specified numbers. For more information, please follow other related articles on the PHP Chinese website!