php8.5
Home/ Manual/ random / randomizer/ Random\Randomizer::shuffleArray

Random\Randomizer::shuffleArray

PHP function Edit on GitHub ✎

(PHP 8 >= 8.2.0)

Get a permutation of an array

Description

Random\Randomizer::shuffleArray(array $array): array

Returns a uniformly selected permutation of the input array.

Each possible permutation of the input array is equally likely to be returned.

Parameters

array

The Array whose values are shuffled.

The input Array will not be modified.

Return Values

A permutation of the values of array.

Array keys of the input array will not be preserved; the returned Array will be a list (array_is_list()).

Errors/Exceptions

Examples

Random\Randomizer::shuffleArray() example

php
<?php
$r = new \Random\Randomizer();

$fruits = [ 'red' => '🍎', 'green' => '🥝', 'yellow' => '🍌', 'pink' => '🍑', 'purple' => '🍇' ];

// Shuffle array:
echo "Salad: ", implode(', ', $r->shuffleArray($fruits)), "\n";

// Shuffle again:
echo "Another Salad: ", implode(', ', $r->shuffleArray($fruits)), "\n";
?>

The above example will output something similar to:

output
Salad: 🍎, 🥝, 🍇, 🍌, 🍑
Another Salad: 🍑, 🍇, 🥝, 🍎, 🍌

Source: reference/random/random/randomizer/shufflearray.xml · from the official PHP manual (php/doc-en)