array_rand
array_rand(array $array, int $num = 1): int|string|array
从数组中随机抽取一个或多个键(单抽返回键本身,多抽返回按原顺序排列的键数组)。7.1 起与 mt_rand 共享全局梅森旋转器,mt_srand 播种后可复现;非密码学安全。
C C23
#include <stdint.h>
#include <stdio.h>
static uint32_t s = 42;
static uint32_t next(void) { // xorshift32:袖珍确定性 PRNG(libc rand() 随平台而异)
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); // 取模有轻微偏差;安全敏感代码不要用
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); // 与 PHP array_rand 同属梅森旋转族;播种即可复现
std::vector<int> nums(20);
for (int i = 0; i < 20; i++) nums[i] = i + 1;
// uniform_int_distribution 的映射是实现定义的(libstdc++ 与 libc++ 不同);
// mt19937 引擎本身是标准化的,原始抽取跨平台一致。% 20 有轻微偏差,安全场景避免。
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); // 播种的 Random 重放同一序列
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)) // 独立播种源:文档承诺确定性
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); // 播种的 Random 重放同一序列
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() 不可播种;袖珍 mulberry32 保证示例可复现
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 播种全局梅森旋转器;array_rand 共享它,故结果可复现
mt_srand(42);
$nums = range(1, 20);
echo json_encode(array_rand($nums)), "\n"; // 取一个:返回单个键
echo json_encode(array_rand($nums, 3)), "\n"; // 取多个:键按原数组顺序返回
$assoc = ["a" => 10, "b" => 20, "c" => 30];
echo json_encode(array_rand($assoc)), "\n"; // 字符串键原样返回
2 [7,14,16] "a"
Python v3.15.2
import random
rng = random.Random(42) # 独立播种生成器;不触碰全局模块状态
nums = list(range(1, 21))
print(nums[rng.randrange(len(nums))])
print(rng.sample(nums, 3)) # sample 采互异的元素
4 [1, 9, 8]
Rust v1.99.1
struct Rng(u32);
impl Rng {
fn next(&mut self) -> u32 { // xorshift32:std 无 RNG(crate 生态用 rand::rngs::StdRng)
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() 不可播种;袖珍 mulberry32 保证示例可复现
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
语言差异说明
C:libc 'rand()' 序列随平台而异(glibc/musl/Windows 各不同),示例改用自实现 xorshift32 保证跨平台可复现;'% n' 取模有偏差。
C++:'std::mt19937' 与 PHP array_rand 同属梅森旋转族,播种后完全可移植;'uniform_int_distribution' 消除取模偏差。
C#:'new Random(seed)' 重放同一序列;高并发场景共享实例有线程问题,'Random.Shared' 不可播种。
Go:'rand.NewSource(seed)' 文档承诺确定性序列。
Java:'new Random(seed)' 算法由规范定死,跨平台一致。
JavaScript:'Math.random()' 不可播种,需要可复现序列时自带 PRNG(示例 mulberry32)。
PHP:手册明示 7.1 起内部算法改为梅森旋转并与 'mt_rand' 共享全局状态,'mt_srand(42)' 可让输出完全复现(本机 PHP 8.6 实测:两次同种子运行结果逐字节一致);返回键而非值;num>1 时返回键数组且按原数组顺序排列(本例 [7,14,16]);空数组或越界 num 抛 ValueError;非密码学安全,敏感场景用 'random_int()' 或 'Random\\Randomizer'。
Python:'random.Random(seed)' 独立实例不影响全局态;'sample' 采互异元素;全局 'random.seed' 有共享状态副作用。
Rust:std 无 RNG;crate 生态 'rand' 的 'seq::SliceRandom::choose' 是惯用采样法,示例用 xorshift32 自足实现。
TypeScript:同 JavaScript。