update page now

shuffle

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

shuffleMescola un array

Descrizione

shuffle(array $array): void

Questa funzione mescola un array (rende casuale l'ordine degli elementi).

Example #1 esempio di shuffle()

<?php
$numeri
= range(1, 20);
srand((float)microtime() * 1000000);
shuffle($numeri);
while (list(,
$numero) = each($numeri)) {
echo
"$numero ";
}
?>

Nota: Dal PHP 4.2.0, non c'è più bisogno di inizializzare il generatore di nomeri casuali con srand() o mt_srand() dal momento che questo viene fatto automaricamente.

Vedere anche arsort(), asort(), ksort(), rsort(), sort() e usort().

add a note

User Contributed Notes 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