如何比较数组的每个元素?

1 php arrays unique

我想比较数组的每个元素.

 $char=array();    
 for($i=0;$i<=10;$i++)
 {
        $char[$i]=rand(0,35);
 }
Run Code Online (Sandbox Code Playgroud)

我想比较$ char数组的每个元素.如果有任何重复值,它应该更改值并选择另一个在数组中应该唯一的随机值.

Jon*_*Jon 7

在这个特定的例子中,可能值的范围非常小,最好以另一种方式执行此操作:

$allPossible = range(0, 35);
shuffle($allPossible);

// Guaranteed exactly 10 unique numbers in the range [0, 35]
$char = array_slice($allPossible, 0, 10);
Run Code Online (Sandbox Code Playgroud)

或者使用等效版本array_rand:

$allPossible = range(0, 35);
$char = array_rand(array_flip($allPossible), 10);
Run Code Online (Sandbox Code Playgroud)

如果值的范围较大,那么这种方法将非常浪费,您应该检查每次迭代的唯一性:

$char = array();
for ($i = 0; $i < 10; ++$i) {
    $value = null;

    // Try random numbers until you find one that does not already exist
    while($value === null || in_array($value, $char)) {
        $value = rand(0, 35);
    }

    $char[] = $value;
}
Run Code Online (Sandbox Code Playgroud)

但是,这是一种概率方法,可能需要花费大量时间才能完成,具体取决于输出的输出rand(如果您想要的值的数量接近所有可能值的数量,则会特别糟糕).

另外,如果您想要选择的值的数量较大(比如超过50左右),那么in_array可以证明是一个瓶颈.在这种情况下,使用数组键检查唯一性而不是值应该更快,因为搜索键的存在是恒定时间而不是线性:

$char = array();
for ($i = 0; $i < 100; ++$i) {
    $value = null;

    // Try random numbers until you find one that does not already exist
    while($value === null || array_key_exists($char, $value)) {
        $value = rand(0, 1000);
    }

    $char[$value] = $value;
}

$char = array_values($char); // reindex keys to start from 0
Run Code Online (Sandbox Code Playgroud)