array_rand
array_rand(array $array, int $num = 1): int|string|array
Picks one or more random keys from an array (a single pick returns the key itself; multiple picks return keys in original order). Since 7.1 it shares the global Mersenne Twister with mt_rand, so mt_srand makes it reproducible; not cryptographically secure.
C C23
#include <stdint.h>
#include <stdio.h>
static uint32_t s = 42;
static uint32_t next(void) { // xorshift32: a tiny deterministic PRNG (libc rand() differs across platforms)
s ^= s << 13; s ^= s >> 17; s ^= s << 5;
return s;
}
int main(void) {
int nums[20];
for (int i = 0; i < 20; i++) nums[i] = i + 1;
int k = (int)(next() % 20); // modulo has a slight bias; avoid in security-sensitive code
printf("key=%d value=%d\n", k, nums[k]);
return 0;
}
key=12 value=13
C++ C++26
#include <iostream>
#include <random>
#include <vector>
int main() {
std::mt19937 rng(42); // the same Mersenne Twister family PHP array_rand uses; seeded = reproducible
std::vector<int> nums(20);
for (int i = 0; i < 20; i++) nums[i] = i + 1;
// uniform_int_distribution's mapping is implementation-defined (libstdc++ vs libc++
// differ); the mt19937 ENGINE itself is standardized, so raw draws are cross-platform.
// % 20 has a slight bias; avoid in security-sensitive code.
std::cout << nums[rng() % 20] << "\n";
std::cout << nums[rng() % 20] << "\n";
return 0;
}
3 8
C# v11.0.100
var rng = new Random(42); // a seeded Random replays the same sequence
var nums = Enumerable.Range(1, 20).ToArray();
Console.WriteLine(nums[rng.Next(nums.Length)]);
Console.WriteLine(nums[rng.Next(nums.Length)]);
14 3
Go v1.27.4
package main
import (
"fmt"
"math/rand"
)
func main() {
rng := rand.New(rand.NewSource(42)) // a dedicated seeded source: documented as deterministic
nums := make([]int, 20)
for i := range nums {
nums[i] = i + 1
}
fmt.Println(nums[rng.Intn(len(nums))])
fmt.Println(nums[rng.Intn(len(nums))])
}
6 8
Java v27.0.1
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rng = new Random(42); // seeded Random replays the same sequence
int[] nums = new int[20];
for (int i = 0; i < nums.length; i++) nums[i] = i + 1;
System.out.println(nums[rng.nextInt(nums.length)]);
System.out.println(nums[rng.nextInt(nums.length)]);
}
}
11 4
JavaScript v26.13.1
// Math.random() cannot be seeded; a tiny mulberry32 keeps the demo reproducible
let s = 42;
function rand() {
s |= 0; s = (s + 0x6d2b79f5) | 0;
let t = Math.imul(s ^ (s >>> 15), 1 | s);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
const nums = Array.from({ length: 20 }, (_, i) => i + 1);
console.log(nums[Math.floor(rand() * nums.length)]);
console.log(nums[Math.floor(rand() * nums.length)]);
13 9
PHP v8.6.0
// mt_srand seeds the global Mersenne Twister; array_rand shares it, so results are reproducible
mt_srand(42);
$nums = range(1, 20);
echo json_encode(array_rand($nums)), "\n"; // one pick: a single key
echo json_encode(array_rand($nums, 3)), "\n"; // several picks: keys in original order
$assoc = ["a" => 10, "b" => 20, "c" => 30];
echo json_encode(array_rand($assoc)), "\n"; // string keys come back as-is
2 [7,14,16] "a"
Python v3.15.2
import random
rng = random.Random(42) # a dedicated seeded generator; the global module state stays untouched
nums = list(range(1, 21))
print(nums[rng.randrange(len(nums))])
print(rng.sample(nums, 3)) # sample picks distinct entries
4 [1, 9, 8]
Rust v1.99.1
struct Rng(u32);
impl Rng {
fn next(&mut self) -> u32 { // xorshift32: std has no RNG (rand::rngs::StdRng is the crate way)
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 17;
self.0 ^= self.0 << 5;
self.0
}
}
fn main() {
let mut rng = Rng(42);
let nums: Vec<i32> = (1..=20).collect();
println!("{}", nums[(rng.next() % 20) as usize]);
println!("{}", nums[(rng.next() % 20) as usize]);
}
13 9
TypeScript v26.13.1
// Math.random() cannot be seeded; a tiny mulberry32 keeps the demo reproducible
let s = 42;
function rand(): number {
s |= 0; s = (s + 0x6d2b79f5) | 0;
let t = Math.imul(s ^ (s >>> 15), 1 | s);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
const nums: number[] = Array.from({ length: 20 }, (_, i) => i + 1);
console.log(nums[Math.floor(rand() * nums.length)]);
console.log(nums[Math.floor(rand() * nums.length)]);
13 9
Language differences
C: the libc 'rand()' sequence varies by platform (glibc/musl/Windows all differ) — the sample uses a self-contained xorshift32 for cross-platform reproducibility; '% n' modulo is biased.
C++: 'std::mt19937' is the same Mersenne Twister family PHP array_rand uses, fully portable once seeded; 'uniform_int_distribution' removes the modulo bias.
C#: 'new Random(seed)' replays the same sequence; a shared instance has thread-safety issues under concurrency, and 'Random.Shared' cannot be seeded.
Go: 'rand.NewSource(seed)' is documented to produce a deterministic sequence.
Java: 'new Random(seed)' pins the algorithm in the specification, identical across platforms.
JavaScript: 'Math.random()' cannot be seeded — bring your own PRNG for reproducible sequences (mulberry32 in the sample).
PHP: the manual states the internal algorithm became the Mersenne Twister in 7.1, sharing global state with 'mt_rand', so 'mt_srand(42)' makes the output fully reproducible (verified locally on PHP 8.6: two same-seed runs agree byte for byte); it returns the key, not the value; with num > 1 it returns an array of keys in original array order ([7,14,16] here); an empty array or an out-of-range num throws ValueError; it is not cryptographically secure — use 'random_int()' or 'Random\\Randomizer' for sensitive cases.
Python: 'random.Random(seed)' is an isolated instance and does not touch global state; 'sample' picks distinct entries; the global 'random.seed' has shared-state side effects.
Rust: std has no RNG; the 'rand' crate's 'seq::SliceRandom::choose' is the idiomatic sampling API — the sample uses a self-contained xorshift32.
TypeScript: same as JavaScript.