Jump to content

[SOLVED] drawing numbers


kryppienation

Recommended Posts

I am trying to draw 5 random numbers between 1 and 99, the problem I'm having is trying to make sure all the numbers are different. I am wondering if someone can help me actually have this check to make sure that all 5 numbers are different or even if there is some better way for me to accomplish this.

 

<?php

$C = 0;

while($C <= 4){

$drawing = rand(1, 99);

echo ''.$drawing.'.';

$C++;
}

?>

Link to comment
https://forums.phpfreaks.com/topic/166944-solved-drawing-numbers/
Share on other sites

<?php

$C = 0;

while($C <= 4){

$drawing = rand(1, 99);
$drawings[$C] = $drawing;
for ($n = 0; $n <= $C; $n++)
{
if ($drawing==$drawings[$n])
{
while ($drawing==$drawings[$n])
{
$drawing = rand(1, 99);
$drawings[$C] = $drawing;
}
}
}

echo ''.$drawing.'.';

$C++;
}

?>

 

There, I think that should work

$numberset = range(1,99);
shuffle($numberset);
for ($i = 1; $i <= 5; $i++) {
   echo array_pop($numberset).'<br />';
}

 

Thank you very much this seems to work excellent, I'm wondering tho, is there anyway that i can assign a variable to each number? I would really like to be able to work with these 5 numbers as separate variables so that they can be called upon later in the code.

that's simply a matter of assigning the array_pop() expression to a variable instead of echoing it:

 

<?php
$numberset = range(1,99);
shuffle($numberset);
$numbers = array();
for ($i = 1; $i <= 5; $i++) {
   $numbers[] = array_pop($numberset);
}
echo '<pre>'.print_r($numbers, TRUE).'</pre>';
?>

Thank you very much this seems to work excellent, I'm wondering tho, is there anyway that i can assign a variable to each number? I would really like to be able to work with these 5 numbers as separate variables so that they can be called upon later in the code.

$numberset = range(1,99);
shuffle($numberset);
for ($i = 1; $i <= 5; $i++) {
   $var = 'number'.$i;
   $$var = array_pop($numberset);
}
echo $number1.' '.$number2.' '.$number3.' '.$number4.' '.$number5.'<br />';

But you'd be better assigning the values into an array

$numberset = range(1,99);
shuffle($numberset);
$numbers = array_slice($numberset,0,5);

echo $numbers[0].' '.$numbers[1].' '.$numbers[2].' '.$numbers[3].' '.$numbers[4].'<br />';

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.