0

How would I set PHP to randomly chose between these two sets of variables to use:

$key = goop;
$john = heck yeah;

and this

$key = roop;
$john = reck reah;

Thanks ever so much! :)

3 Answers 3

3

For example:

if ( rand(0,1) )
{
    $key = "goop";
    $john = "heck yeah";
}
else
{
    $key = "roop";
    $john = "reck reah";
}
Sign up to request clarification or add additional context in comments.

15 Comments

But it appears that in this example the first set would get a much bigger chance, correct me if I'm wrong.
By far the simplest solution, rand() is an int, so it should be even chance
So I'd have to set the max rand() possible, like this? rand(0, 1); to make it equel? Or is it equel by default?
I'd use mt_rand() as it is faster and should be more random.
Mine will maintain the pairs ;)
|
1

I'd recommend using an array:

$selection = array(
    array('goop', 'heck yeah'),
    array('roop', 'reck reah')
);

shuffle($selection);

list($key, $john) = array_pop($selection);

5 Comments

What about the goop (first set) part? it's not included in the code you provided
How would I accomplish what you did, but with three sets?
Simply add another array into $selection. It'll support as many as you want to add in
Martin, but How would I make $list a variable? Could you also provide a working demo of the PHP code?
@SolèneLeVan list is a function -- it assigns the array values to the variables $key and $john
0

Store the values in an array, and then use rand() to generate the values:

$key_vals = array('goop', 'roop', 'toop');
$john_vals = array('heck yeah', 'reck reah', 'leck leah');

$key = $key_vals[rand(0, (count($key_vals) - 1))];
$john = $john_vals[rand(0, (count($john_vals) - 1))];

You can easily extend this by adding values to the respective arrays, and increasing the maximum random number (i.e. second argument in rand()).

11 Comments

+1 Good stuff. But I'll choose ribot's as the answer. Thanks!
No problem - there's more than one way to skin a cat :)
See my updated answer on how to extend this to include more values.
How would I accomplish what you did, but with three sets?
If the pairs always have to match (i.e. goop with heck yeah) it'd be better to use Martin's answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.