Getting Random Values from an Array

Getting Random Values from an Array




There is a great PHP built-in function to call random values from an array easily array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key.




How to Use array_rand()

You have to set array value and optionally you can define number of returned value.

array_rand($arrayname, $numberofreturn);

Array_rand() Sample

Sample below will choose 2 users and print as an array

$user_names = ["John", "Mike", "Mary", "Leo"];

$random_users = array_rand($user_names, 2);

print_r($random_users);

Getting Random Values from an Array is possible php built in array function array_rand()


array_rand