Log in

View Full Version : Possible to use array to set a random value?



BLiZZaRD
07-09-2006, 08:34 AM
Okay so that title might not be the best inthe world. What I have is a script where I am using math over a period of time.

I just started writing the script as an idea I had and wanted to try some php with it.

I have made an array of numbers for the value:



$value=array(1, 2, 4, 8, 16);
$valtot= '31';


So then I made some check boxes:



<table>
<tr>
<td>
<input type="checkbox" name="choice1" value=""> Choice 1
</td>
<td>
<input type="checkbox" name="choice2" value=""> Choice 2
</td>
<td>
<input type="checkbox" name="choice3" value=""> Choice 3
</td>
<td>
<input type="checkbox" name="choice4" value=""> Choice 4
</td>
</tr>
</table>

What I am attempting to accomplish next is adding something to the value="" line in the check boxes that I can use for the math part of the script.

I also want the values to be random each time I load the scritp, BUT ONLY the FIRST TIME.

As you can see there is one more value than there are check box options. SO I want the value of the check box to be random, thus leaving one out. Then I will select one or 2 checkboxes, click a button, and it will do the math. then when the math is complete I will select another box (as the others will remain checked) then do another math check.

Then if I refresh the page, NEW values are given to the check boxes, so I could invariably choose the same options each time and get different results.

Does that make sense?

Okay, good. So what I guess I am after then is a way to pull a number randomly from the array and attatch it to a checkbox. :confused:

BLiZZaRD
07-09-2006, 11:05 AM
Okay so after some trial and error I have found the use of the


$rand_keys=array_rand($value,5);


tag. I have placed this inside the tabe, but echoe'd after the Choice 1 text, so basically it is there, but not "assigned" to the choice checkbox it is with.

Is there a way to make choice 1 BE the random number generated by the $rand_keys thing?

Twey
07-09-2006, 11:28 AM
for($i = 1; $i <= 4; ++$i) {
$rnd = rand(0, count($value));
echo('<label><input type="checkbox" name="choice' . $i . '" value="' . $value[$rnd] . '"> Choice ' . $i . '</label>');
unset($value[$rnd]); // Prevent the same value appearing twice
}

BLiZZaRD
07-09-2006, 11:31 AM
Very nice! Now I can move onto the Math parts! Thanks Twey!

BLiZZaRD
07-09-2006, 11:36 AM
Also, just to clarify that you were in FACT just testing me..



$rnd = rand(0, cout($value));


needs to be couNt not cout :D

Twey
07-09-2006, 11:37 AM
Gah, sorry. Stuck halfway between languages again. :)

That code will make mincemeat of your array, by the way, so you might want to keep a copy somewhere.

BLiZZaRD
07-09-2006, 11:37 AM
LOL just made a back up before I did it. Always do ;)