imgrooot Posted April 15, 2019 Share Posted April 15, 2019 Say I have two variables like below. I basically want to select one of them, but through random choice. How do I do that? $orange = 'Orange'; $apple = 'Apple'; Link to comment Share on other sites More sharing options...
requinix Posted April 15, 2019 Share Posted April 15, 2019 Use mt_rand() to generate a random number. Link to comment Share on other sites More sharing options...
NotionCommotion Posted April 15, 2019 Share Posted April 15, 2019 To expand on requinix's response: $options = ['Orange', 'Apple', 'Pear']; $select=mt_rand(0,2); $selected=$options[$select]; Link to comment Share on other sites More sharing options...
chhorn Posted April 15, 2019 Share Posted April 15, 2019 or just array_rand([$orange, $apple]); Link to comment Share on other sites More sharing options...
Psycho Posted April 17, 2019 Share Posted April 17, 2019 On 4/15/2019 at 8:24 AM, chhorn said: or just array_rand([$orange, $apple]); array_rand only returns the key (or keys) of the randomly selected items. So, that line would only return a 0 or 1 - which is not helpful without the original array to get the value from. It makes more sense to create an array as a variable first, the use array rand to get the value like so: $values = ['orange', 'apple']; $randomValue = $values[array_rand($values)]; Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.