The array_rand() function is used to get a random value from an array. This function accepts an array as a parameter and returns a random key from the array.
The array_rand() function takes two parameters. One is the array from which you want to get the random key.
$array: [Required] This is a required parameter that array_rand() takes.
$number_of_items: [Optional] this is the int value that shows how many random keys you want to get from the array. Its value is set to 1 by default.
<?php $my_arr = ["James", "Stark", "Suart", "Rajesh", "Troy"]; $rand_index = array_rand($my_arr); echo $my_arr[$rand_index]; ?>
We can also write the above code example in one line as below.
The output will be different each time you execute the above code. If you want to get more than 1 random key from the array you can use the below code example.
<?php $my_arr = ["James", "Stark", "Suart", "Rajesh", "Troy"]; $rand_index = array_rand($my_arr, 2); echo $my_arr[$rand_index]; echo $my_arr[$rand_index]; ?>
The above code is an example of how to generate a random item from an array using the PHP function array_rand(). The function takes two arguments - the array to select from and the number of items to select. In this case, two items are selected and their indices are stored in the $rand_index array. The items themselves are then echoed back to the screen.
If you're looking for a quick and easy way to get a random item from an array using PHP, the shuffle() function is the way to go. This function will randomly shuffle the items in an array, making it easy to get a random item.
<?php $my_arr = [ "a" => 100, "b" => 200, "c" => 300, "4" => 400 ]; shuffle($my_arr); echo $my_arr; ?>
The shuffle() function used in the above PHP code will randomize the order of the elements in the array, and then the echo statement will print out the first element in the array.
If you need to generate a random number in PHP, the rand() function is the simplest way to do it. This function takes two parameters - the minimum and maximum values for the random number. For example, if you wanted a random number between 1 and 10, you would use rand(1, 10).
<?php $arr = [100, 200, 300, 400, 500]; echo $arr[rand(0, count($arr) - 1)]; ?>
This code generates a random number between 0 and 4, and then outputs the corresponding value from the $arr array.