How to Pick One or More Random Keys Out of an Array Using PHP?

Using PHP, you can use the `array_rand()` function to pick one or more random keys from an array.

Syntax:-

<?php
array_rand(array $array, int $num = 1): int|string|array
?>

1. `$array`: The input array.
2. `$num`: The number of random keys to pick.
3. Returns:** A single key (if `$num = 1`) or an array of keys (if `$num > 1`).

Example 1: Pick One Random Key

<?php
$colors = ['red', 'blue', 'green', 'yellow', 'black'];
$randomKey = array_rand($colors); // Get a single random key
$randomValue = $colors[$randomKey]; // Get the corresponding value
echo "Random Key: $randomKey, Random Value: $randomValue";
?>

Output (Example)

Random Key: 2, Random Value: green

Example 2: Pick Multiple Random Keys

<?php
$fruits = ['apple', 'banana', 'orange', 'grape', 'mango'];
$randomKeys = array_rand($fruits, 3); // Pick 3 random keys

foreach ($randomKeys as $key) {
echo "Random Key: $key, Value: " . $fruits[$key] . "\n";
}
?>

Output (Example)

Random Key: 1, Value: banana
Random Key: 4, Value: mango
Random Key: 2, Value: orange

Example 3: Get Random Key-Value Pairs

<?php
$users = [
"u1" => "Alice",
"u2" => "Bob",
"u3" => "Charlie",
"u4" => "David"
];

$randomKeys = array_rand($users, 2); // Pick 2 random keys
$randomUsers = array_intersect_key($users, array_flip($randomKeys)); // Get key-value pairs
print_r($randomUsers);
?>

Output (Example)

Array
(
[u2] => Bob
[u4] => David
)

Notes

1. `array_rand()` returns keys, not values.
2. Use `array_intersect_key()` to get both keys and values.
3. If `$num` is greater than the array size, it will throw a warning.