Problem:
You’ve an array which has some elements. You want to pick one (or more) item randomly each time from the array.
Solution:
You can use array_rand() function. array_rand() function randomly selects one or more items from an array and actually returns corresponding key(s) of the selected item(s). See the following examples-
To select one random item from the Array-
<?php $abc = array(22, 3, 45, 476, 120, 786); $random_key = array_rand($abc); echo $abc[$random_key]; ?>
[wpdm_file id=83]
Output:
45 (you may get different number)
How it works:
As we’ve not mentioned the second parameter in the above array_rand() function, it randomly selectes just one item (here, it is 45) from the $abc[] array and returns its key (which is 2 here). To print the that key, we use $abc[$random_key]; You could also mention 1 in the second parameter which brings the same result.
To select multiple random items from the Array –
<?php $abc = array(22, 3, 45, 476, 120, 786); $random_key_arr = array_rand($abc, 2); echo $abc[$random_key_arr[0]] . "<br />"; echo $abc[$random_key_arr[1]] . "<br />"; ?>
[wpdm_file id=84]
Output:
22 (you may get different value)120 (you may get different value)
How it works:
When you mention a number which is greater than 1 in the second parameter of the array_rand() function, it randomly selects that number of items and returns their keys as an array. In the above example, the returned keys are 0 and 4. And, at last, we used the keys to print those items.