views:

72

answers:

3

For this Wordpress site, I need to generate 24 variables each of which contains a number between 1 and 24. The problem is that two variables cannot have the same value. So I basically need to generate 24 variables each of which contains a number between 1 and 24.

Here's the code that I am using to generate a random number.

$mirza = rand(1,24);

Thanks for any help.

+8  A: 

You can use shuffle

$numbers = range(1, 24);
shuffle($numbers);
nico
+1 you beat me to it :P
GWW
@GWW: stop reading my mind! :P
nico
@nico If only the ability didn't have a 20 second lag period.
GWW
How would i lets say store the shuffle values in 24 different variables?I tried this: $numbers = range(1, 24); $one = shuffle($numbers); $two = shuffle($numbers); echo $one; echo '<br />3'; echo $two;
mirza
@mirza: `$numbers` is an array of 24 elements, so it is like having 24 variables. You just access them with `$numbers[0]`, `$numbers[1]`, and so on up to `$numbers[23]`. The whole point of using arrays is not to have lots of variables around. Of course you could do `$one = $numbers[0]`, `$two = $numbers[1]` etc. but that would be pointless.
nico
@mirza: also, note that `shuffle` does NOT return a shuffled version of the array, it modifies the original variable. The return value is just the status of the call (`TRUE` or `FALSE` for success or failure)
nico
@mirza if you are dead set no not using an array you could use list($a1, $a2, ... , $a24) = $numbers; (fill in the ... with the rest of the variable names)
GWW
+4  A: 
$a = range(1,24);
shuffle ( $a );
GWW
+1  A: 

What you're looking for is not 24 truly random numbers (which could randomly be all identical... although the odds are not in your favour), but actually just a shuffling algorithm.

Try shuffle on an array in PHP instead.

Rudu