shuffle

shuffle(array &$array): true

Shuffles array elements randomly (values kept, keys rebuilt as integers; associative keys lost); not cryptographically secure, seedability only via the global mt_srand.

C C23

C23
#include <stdio.h>
#include <stdlib.h>

static void fisher_yates(int *a, int n) {
    for (int i = n - 1; i > 0; i--) {
        int j = rand() % (i + 1);
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
}

static int equal(const int *a, const int *b, int n) {
    for (int i = 0; i < n; i++) {
        if (a[i] != b[i]) return 0;
    }
    return 1;
}

int main(void) {
    /* C has no built-in shuffle: Fisher-Yates by hand; srand(seed) makes the
       permutation repeatable (same-seed reruns must agree within one libc) */
    int orig[5] = {1, 2, 3, 4, 5};
    int a[5], b[5];
    srand(2026);
    for (int i = 0; i < 5; i++) a[i] = orig[i];
    fisher_yates(a, 5);
    srand(2026);
    for (int i = 0; i < 5; i++) b[i] = orig[i];
    fisher_yates(b, 5);
    printf("%d\n", equal(a, b, 5));
    /* Derived fact: sorting the shuffled array restores the original */
    int c[5] = {1, 2, 3, 4, 5};
    srand(7);
    fisher_yates(c, 5);
    for (int i = 1; i < 5; i++) {
        int key = c[i], j = i - 1;
        while (j >= 0 && c[j] > key) { c[j + 1] = c[j]; j--; }
        c[j + 1] = key;
    }
    printf("%d\n", equal(c, orig, 5));
    return 0;
}
Output
1
1

C++ C++26

C++26
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>

int main() {
    // std::shuffle with a seeded mt19937: same-binary reruns repeat the
    // permutation (distribution mapping is per-standard-library)
    std::vector<int> original = {1, 2, 3, 4, 5};
    std::vector<int> a = original;
    std::mt19937 g1(2026);
    std::shuffle(a.begin(), a.end(), g1);
    std::vector<int> b = original;
    std::mt19937 g2(2026);
    std::shuffle(b.begin(), b.end(), g2);
    std::cout << std::boolalpha << (a == b) << "\n";
    // Derived fact: sorting the shuffled vector restores the original
    std::vector<int> c = original;
    std::mt19937 g3(7);
    std::shuffle(c.begin(), c.end(), g3);
    std::sort(c.begin(), c.end());
    std::cout << (c == original) << "\n";
    return 0;
}
Output
true
true

C# v11.0.100

v11.0.100
// No built-in shuffle: hand-write Fisher-Yates with a seedable Random
int[] original = { 1, 2, 3, 4, 5 };
var rng1 = new Random(2026);
int[] a = (int[])original.Clone();
FisherYates(a, rng1);
var rng2 = new Random(2026);
int[] b = (int[])original.Clone();
FisherYates(b, rng2);
Console.WriteLine(a.SequenceEqual(b));
// Derived fact: sorting the shuffled array restores the original
var rng3 = new Random(7);
int[] c = (int[])original.Clone();
FisherYates(c, rng3);
Array.Sort(c);
Console.WriteLine(c.SequenceEqual(original));

static void FisherYates(int[] arr, Random rng)
{
    for (int i = arr.Length - 1; i > 0; i--)
    {
        int j = rng.Next(i + 1);
        (arr[i], arr[j]) = (arr[j], arr[i]);
    }
}
Output
True
True

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"math/rand"
	"sort"
)

func shuffled(seed int64, src []int) []int {
	// rand.Shuffle with its own *rand.Rand: a fixed seed repeats the
	// permutation exactly
	r := rand.New(rand.NewSource(seed))
	out := append([]int(nil), src...)
	r.Shuffle(len(out), func(i, j int) { out[i], out[j] = out[j], out[i] })
	return out
}

func main() {
	original := []int{1, 2, 3, 4, 5}
	fmt.Println(fmt.Sprint(shuffled(2026, original)) == fmt.Sprint(shuffled(2026, original)))
	restored := shuffled(7, original)
	sort.Ints(restored)
	fmt.Println(fmt.Sprint(restored) == fmt.Sprint(original))
}
Output
true
true

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class Main {
    public static void main(String[] args) {
        // Collections.shuffle accepts an explicit Random: a fixed seed repeats
        // the permutation exactly
        List<Integer> original = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> a = new ArrayList<>(original);
        Collections.shuffle(a, new Random(2026));
        List<Integer> b = new ArrayList<>(original);
        Collections.shuffle(b, new Random(2026));
        System.out.println(a.equals(b));
        // Derived fact: sorting the shuffled list restores the original
        List<Integer> c = new ArrayList<>(original);
        Collections.shuffle(c, new Random(7));
        Collections.sort(c);
        System.out.println(c.equals(original));
    }
}
Output
true
true

JavaScript v26.13.1

v26.13.1
// JS has no built-in shuffle: hand-write Fisher-Yates (the same algorithm
// behind PHP shuffle / Python random.shuffle). Math.random is not seedable,
// so only derived facts print
function shuffle(arr) {
    const a = [...arr];
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}
const original = [1, 2, 3, 4, 5, 6];
const mixed = shuffle(original);
console.log(mixed.length === original.length);
console.log([...mixed].sort((x, y) => x - y).join() === original.join());
console.log(original.join());
Output
true
true
1,2,3,4,5,6

PHP v8.6.0

v8.6.0
// shuffle keeps values but rebuilds integer keys (associative keys are lost)
$a = ['k1' => 'v1', 'k2' => 'v2', 'k3' => 'v3'];
shuffle($a);
var_dump(array_keys($a) === range(0, 2));
var_dump(count(array_diff(['v1', 'v2', 'v3'], $a)) === 0);
// Derived fact: sorting the shuffled array restores the original exactly
$b = range(1, 6);
shuffle($b);
sort($b);
var_dump($b === range(1, 6));
// Manual: the random source is the global Mt19937 - a fixed mt_srand seed
// makes shuffle repeatable even though shuffle itself takes no seed parameter
$x = range(1, 5);
mt_srand(2026);
shuffle($x);
$y = range(1, 5);
mt_srand(2026);
shuffle($y);
var_dump($x === $y);
Output
bool(true)
bool(true)
bool(true)
bool(true)

Python v3.15.2

v3.15.2
import random

# random.shuffle is seedable via random.Random(seed): same seed -> same
# permutation (PHP shuffle has no seed parameter; it only repeats through
# the global mt_srand, which its manual documents)
rng = random.Random(2026)
a = [1, 2, 3, 4, 5]
rng.shuffle(a)
b = [1, 2, 3, 4, 5]
random.Random(2026).shuffle(b)
print(a == b)
# Derived fact: sorting the shuffled list restores the original
c = [1, 2, 3, 4, 5, 6]
random.Random(7).shuffle(c)
print(sorted(c) == [1, 2, 3, 4, 5, 6])
Output
True
True

Rust v1.99.1

v1.99.1
use rand::prelude::*;

fn main() {
    // rand crate: a seedable RNG repeats the permutation exactly;
    // SliceRandom::shuffle is Fisher-Yates internally
    let original = [1i32, 2, 3, 4, 5];
    let mut a = original;
    let mut rng1 = StdRng::seed_from_u64(2026);
    a.shuffle(&mut rng1);
    let mut b = original;
    let mut rng2 = StdRng::seed_from_u64(2026);
    b.shuffle(&mut rng2);
    println!("{}", a == b);
    // Derived fact: sorting the shuffled vec restores the original
    let mut c = original;
    let mut rng3 = StdRng::seed_from_u64(7);
    c.shuffle(&mut rng3);
    c.sort_unstable();
    println!("{}", c == original);
}
Output
true
true

TypeScript v26.13.1

v26.13.1
// No built-in shuffle: hand-write Fisher-Yates over a typed array;
// Math.random is not seedable, so only derived facts print
function shuffle<T>(arr: T[]): T[] {
    const a = [...arr];
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}
const original: number[] = [1, 2, 3, 4, 5, 6];
const mixed = shuffle(original);
console.log(mixed.length === original.length);
console.log([...mixed].sort((x, y) => x - y).join() === original.join());
console.log(original.join());
Output
true
true
1,2,3,4,5,6

Language differences

C: no built-in - hand-write Fisher-Yates (from the tail, swapping with rand() % (i+1) each step); srand(seed) makes it repeatable (fixed sequence per seed within one libc; libc algorithms differ but each is self-consistent). rand() % n has slight modulo bias - use random or division sampling outside teaching snippets.

C++: std::shuffle + seeded std::mt19937 - a standardized algorithm interface; note uniform_int_distribution's mapping is implementation-defined, so permutations may differ across standard libraries, but the same binary reruns identically.

C#: no built-in - hand-written Fisher-Yates with new Random(seed) (.NET 6+ switched the parameterless constructor to a fresh source, but the seeded constructor stays the reproducible compat algorithm).

Go: rand.Shuffle (Fisher-Yates inside) + an explicit rand.New(rand.NewSource(seed)) - passing the RNG explicitly makes reproducibility natural; the global rand auto-seeds since Go 1.22 (non-reproducible).

Java: Collections.shuffle(list, new Random(seed)) - pass an RNG as the second argument to reproduce; without it, a shared global Random (internally synchronized) is used.

JavaScript: no built-in - hand-write Fisher-Yates; Math.random has no seed mechanism in the standard and cannot repeat (only derived facts print).

PHP: shuffle keeps values but rebuilds keys as consecutive integers (associative keys are gone - the manual states new keys are consecutive); two manual Cautions: not cryptographically secure (use random_int/Random\Randomizer for that) and the random source is the global Mt19937 (shared state with mt_rand); key fact (manual-stated, verified): shuffle has no seed parameter, yet mt_srand(fixed value) makes its output exactly repeatable - opposite of the "PHP shuffle cannot be seeded" intuition. Determinism strategy here: no pre-baked permutations, only the three boolean facts "sort restore == original", "keys rebuilt", "same seed agrees twice".

Python: random.shuffle (Fisher-Yates) - module level uses the global instance (random.seed reproducible), or pass an isolated random.Random(seed); the difference from PHP is that seeding is a first-class API rather than hidden global state.

Rust: rand crate SliceRandom::shuffle (Fisher-Yates inside) + explicit StdRng::seed_from_u64 seeding; rand::seq::index::sample for sampling without replacement.

TypeScript: same as JavaScript - hand-written Fisher-Yates, unseedable Math.random; pass a self-made seeded RNG when reproducibility is needed.