PHP数组中的唯一数字


PHP unique number in array

我试图在一个数组中生成6个数字,我使用的是mt_rand函数,但数组中不能有相同的数字。我该如何检查并再次生成数字?

我曾想过制作一个重复的数组,循环抛出并计算数组中的数量,如果它大于1,则重新生成数字并再次检查,然而,对于php可能有一个我找不到的本地函数的东西来说,这似乎是一项艰巨的工作。。。

重复的事情不是我需要帮助的,那就是检查值的键,我需要所有值都是唯一的。

$number_of_numbers = 6;//number_of_numbers in array
$min = 1;//minimum value of number that you want
$max = 15;//maximum value of number that you want
$array = array();
for ($a = 0; $a < $number_of_numbers; $a++) {
    $check = 0;//for entering while loop
    while ($check !== false) { //pick a number and check if it is in array if it is in the array, pick again and check again
        $try[$a] = mt_rand($min, $max); //pick a number
        $check = array_search($try[$a], $array);// search that number if it is in the array
    }
    $array[] = $try[$a]; //add number to array
}
var_dump($array); // show me the array

你是这个意思吗?我可能会误解数组键。你能再解释一下吗?

这是输出。对不起,我忘了先加。

array(6) { [0]=> int(10) [1]=> int(12) [2]=> int(3) [3]=> int(5) [4]=> int(9) [5]=> int(15) }