PHP 8 reference · Array Sorting Functions
PHP shuffle() Function
Shuffle an array into a random order, in place. Keys are discarded. Not suitable for security-sensitive randomness.
PHP 8 Since 4.0
Syntax
shuffle(array &$array): true
Parameters
| Parameter | Description |
|---|---|
array |
The array to sort (changed in place). |
Return value
Always true.
Examples
<?php
mt_srand(42); // fixed seed so the output is repeatable
$cards = ["A", "K", "Q", "J"];
shuffle($cards);
echo implode(" ", $cards), "\n";
Output
K A J Q
<?php
$r = new Random\Randomizer(new Random\Engine\Mt19937(42));
echo implode(" ", $r->shuffleArray(["A", "K", "Q", "J"])), "\n"; // PHP 8.2+, returns a copy
Output
K A J Q
For secure shuffling (games with real prizes, lotteries) use
(new Random\Randomizer())->shuffleArray($array), which uses a secure engine by default.
Version history
Related
array_rand()· Pick one or more random keys from an array. Use it with the array to get random values; not for security.sort()· Sort an array's values in ascending order, in place. Keys are discarded and the result is renumbered from 0.- PHP Arrays · tutorial
- PHP Array Functions · tutorial