update page now
PHP 8.4.20 Released!

shuffle

(PHP 4, PHP 5, PHP 7, PHP 8)

shuffle打乱数组

说明

shuffle(array &$array): true

本函数打乱(随机排列单元的顺序)一个数组。

警告

本函数并不会生成安全加密的值,并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机,则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例,random_int()random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API

警告

此函数使用全局 Mt19937(“梅森旋转算法”)实例作为随机源,因此与所有其他使用全局 Mt19937 的函数共享其状态。 使用这些函数中的任何一个都会推进所有其他函数的序列,无论作用域如何。

通过向 mt_srand()srand() 以已知值播种来生成可重复的序列也将从此函数产生可重复的输出。

在所有新编写的代码中,建议使用 Random\Randomizer 的方法。

参数

array

待操作的数组。

返回值

总是返回 true

更新日志

版本 说明
7.1.0 内置的随机数产生算法从 libc rand 函数改成» 梅森旋转伪随机数生成算法。

示例

示例 #1 shuffle() 例子

<?php
$numbers
= range(1, 20);
shuffle($numbers);
foreach (
$numbers as $number) {
echo
"$number ";
}
?>

注释

注意: 此函数为 array 中的元素赋与新的键名。这将删除原有的键名,而不是仅仅将键名重新排序。

注意:

重置数组中的内部指针,指向第一个元素。

参见

添加备注

用户贡献的备注 2 notes

up
135
ahmad at ahmadnassri dot com
16 years ago
shuffle for associative arrays, preserves key=>value pairs.
(Based on (Vladimir Kornea of typetango.com)'s function) 

<?php
    function shuffle_assoc(&$array) {
        $keys = array_keys($array);

        shuffle($keys);

        foreach($keys as $key) {
            $new[$key] = $array[$key];
        }

        $array = $new;

        return true;
    }
?>

*note: as of PHP 5.2.10, array_rand's resulting array of keys is no longer shuffled, so we use array_keys + shuffle.
up
4
pineappleclock at gmail dot com
17 years ago
If you want the Power Set (set of all unique subsets) of an array instead of permutations, you can use this simple algorithm:

<?php
/**
* Returns the power set of a one dimensional array,
* a 2-D array.
* array(a,b,c) ->
* array(array(a),array(b),array(c),array(a,b),array(b,c),array(a,b,c))
*/
function powerSet($in,$minLength = 1) { 
   $count = count($in); 
   $members = pow(2,$count); 
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minLength) {
         $return[] = $out;
      }
   }
   return $return;
}
?>
To Top