Home > Backend Development > PHP Tutorial > php method to get random combinations from specified numbers

php method to get random combinations from specified numbers

jacklove
Release: 2023-03-31 06:24:02
Original
1789 people have browsed it

For example: Given the number 100, you need to randomly obtain 3 combinations of 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);?>
Copy after login

Output:

Array(
    [0] => 42
    [1] => 25
    [2] => 33)
Copy after login

This article explains how PHP obtains random combinations from specified numbers. For more related content, please pay attention to the PHP Chinese website.

Related recommendations:

Interpretation of php's PDO connection to the database related content

How to implement recursive acquisition through php code The value of a specified key in an array

Reading a 1G file size through PHP

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template