Input: $arr = ("a" = > "21", "b" = > "31", "c" = > "7", "d" = > "20") // Get one random value Output: 7 Input: $arr = ("a" = > "21", "b" = > "31", "c" = > "7", "d" = > "20") // Get two random values Output: 21 31Method 1:This method discusses the shuffle() function to get a random value from an array in PHP. PHP | Function shuffle() :The shuffle() function - it is a built-in function in PHP that is used to shuffle or randomize the order of elements in an array. This function assigns new keys to the elements in the array. It will also remove all existing keys, rather than just reordering keys and assigning numeric keys starting at zero.Syntax:
bool shuffle ($array)Example :
// Declare an associative array
$arr
=
array
(
"a"
= >
"21"
,
" b "
= >
" 31 "
,
"c"
= >
"7"
,
"d"
= >
"20"
);
// Use the shiffle function to randomly assign a numeric value
// key to all elements of the array.
shuffle (
$arr
);
// Show the first element of the array in random order
echo
$arr
[0];
?>
Exit:31In the above example, the keys of the associative array have been changed. The shuffle() function has randomly assigned keys for items, starting at zero. Since shuffle() is constantly changing the keys of the array.Method 2:Use the array_rand() function to get a random value from an array in PHP. PHP | Array_rand() function :array_rand() function - it is a built-in function in PHP that is used to get a random number of elements from an array. An element is a key and can return one or more keys.Syntax:
array_rand ($array, $num)This the function takes two parameters $array and $num. The $array variable stores the elements of the array, and the $num parameter contains the number of elements to retrieve. The default value for this parameter is 1.Example 1:
// Declare an associative array
$arr
=
array
( "a"
= >
"21"
,
"b"
= >
"31 "
,
" c "
= >
"7"
,
"d"
= >
"20"
);
// Use the array_rand function to return a random key
$key
=
array_rand
(
$arr
);
// Show random array element
echo
$arr
[
$key
];
?>
Exit:21
In the above example, we did not explicitly specify a value for the second parameter, so the default is 1 and array_rand() returns one random key.Example 2: B This example explicitly specifies the value of the second parameter, so the array_rand() function returns an array of random keys.
// Declare an associative array
$arr
=
array
(
"a"
= >
"21"
,
"b"
= >
"31"
,
"c"
= >
"7"
,
"d"
= >
"20"
);
// It specifies the item number
$num
= 2;
// Returns an array of random keys
$keys
=
array_rand
(
$arr
,
$num
);
// Show array element
echo
$arr
[
$keys
[0]].
""
.
$arr
[
$keys
[ one]];
?>
Exit:21 7