Tom Lankhorst · notes

Pick random values from an array in PHP

· php

PHP provides the array_rand( $arr, $num )  function which returns an integer or array containing the keys of the array.

To obtain an array of values the following one-liner can be used:

array_intersect_key( $arr, array_flip( array_rand( $arr, $num ) ) );

This picks \$num random keys from \$arr (array_rand), flips keys with values (array_flip), intersects the picked keys with those of \$arr (array_intersect_keys) and returns the corresponding elements of \$arr.

Getting random values from an array.

This works for \$num > 1 as array_rand returns an integer otherwise. When a single random value is required, the expression becomes simpler:

$arr[ array_rand( $arr ) ];