The array_rand() function selects one or more random keys from an array, while shuffle() randomizes the order of all elements in an array. These functions are commonly used for random selection, games, quizzes, and data shuffling.
array_rand(array, number) → returns one key or an array of keysshuffle(array) → randomizes element order and returns true
// Select a random key from the array
<?php
$fruits = array("apple", "banana", "cherry", "date");
$randomKey = array_rand($fruits);
echo $fruits[$randomKey];
?>
A random key index is returned from $fruits, which is then used to fetch and display the corresponding value.
// Randomly rearrange the array elements
<?php
$numbers = array(1, 2, 3, 4, 5);
shuffle($numbers);
print_r($numbers);
?>
The original array order is changed permanently. No new array is created.
// Pick multiple random keys from the array
<?php
$colors = array("red", "green", "blue", "yellow");
$randomKeys = array_rand($colors, 2);
echo $colors[$randomKeys[0]] . ", " . $colors[$randomKeys[1]];
?>
This illustrates how shuffle works conceptually:
Original: [1, 2, 3, 4, 5]
Shuffled: [3, 1, 5, 2, 4]
array_rand() returns keysshuffle() only when modifying the original array is acceptablearray_rand()