Jump to content

[SOLVED] Picking random


Canman2005

Recommended Posts

Hi all

 

I have the following

 

if(getramdoms(2) != 0)
{
$rr = $rr. '1,';
}
if(getramdoms(44) != 0)
{
$rr = $rr. '2,';
}
if(getramdoms(99) != 0)
{
$rr = $rr. '3,';
}
if(getramdoms(132) != 0)
{
$rr = $rr. '4,';
}

print $rr;

 

which produces something like

 

1,3,4,

 

My question is, how can I randomly pick one of those values and set the random value as

 

$randomnumber = ?

 

any help would be great as im totally stumped

 

thanks very much for any help

Link to comment
Share on other sites

I have tried using

 

$exploded = explode(",", "$rr");
$rand = rand(1, count($exploded));
echo $exploded[$rand];

 

which kinda works, it displays a random number, but sometimes returns nothing (although it could be 0 it's returning)

 

any ideas why it would do that?

Link to comment
Share on other sites

You need to redo how you are creating the values. By concatentating the values into single string with a comma at the end, you are making this more difficult than it needs to be. If you explode the values like Mark suggests you will alwaus have an empty value at the end of the array.

 

Create your values in an array to begin with and then just use array_rand() to get a random value out of that array

 

$rr = array();

if(getramdoms(2) != 0) { $rr[] = 1; }
if(getramdoms(44) != 0) { $rr[] = 2; }
if(getramdoms(99) != 0) { $rr[] = 3; }
if(getramdoms(132) != 0) { $rr[] = 4; }

$randomnumber = array_rand($rr);

Link to comment
Share on other sites

when picking just one entry with array rand, it returns the key of the array, not the value at that key, so the last line to

 

print $rr[$randomnumber];

Yeah, I missed adding that - thanks for the assist. Could also do this

 

$randomnumber = $rr[array_rand($rr)];

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.