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'; Quote 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. Quote 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]; Quote 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]); 1 Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 17, 2019 Share Posted April 17, 2019 (edited) 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)]; Edited April 17, 2019 by Psycho Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.