Jump to content
imgrooot

What's the best way to randomly select a single variable from two variables?

Recommended Posts

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';

 

Share this post


Link to post
Share on other sites

Use mt_rand() to generate a random number.

Share this post


Link to post
Share on other sites
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 by Psycho

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.