␡
- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
3.11 Randomizing the Elements of an Array
You want to randomize all elements in an array.
Technique
Use the shuffle() function, which changes the order of the array elements:
<?php srand ((double)microtime()*1000000); $some_array = range(1, 52); shuffle($some_array); // $some_array now contains numbers from 1 to 52 in random order. ?>
Comments
The shuffle() function is extremely useful for randomizing arrays because it saves you the time of writing your own complex routine. This can be useful if, for example, you make an online poker game or dice game and want the results to be completely random.