Jump to content

Recommended Posts

The answer is yes, a few minutes ago I posted this for someone who wanted to simulate the lottery:

$numbers = array();

function draw() {
   return rand(1,59);
}

for ($i=0; sizeof($numbers) < 6; $i++) {
   $new = draw();
   if (in_array($new, $numbers)) {
      $new = draw ();
   } else {
      $numbers[] = $new;       
   }
}

var_dump($numbers);

Good example, but the trouble with that is if the draw() number exists it will generate another draw() number without verifying if that also exists. Would be better to define the numbers and have them removed from a number map so they cannot possibly re-occur. Of course, there may also be a better way..

I don't know about better, but this is the way I code things like the example given:

$numbers = array();

function draw() {
   return rand(1,59);
}

while (count($numbers) < 6){
   do {
       $new = draw();
   } while (in_array($new, $numbers));
   $numbers[] = $new;       
}

var_dump($numbers);

 

@UrbanDweller functions don't care where they are called from, they still work the same.  when you call a function the code jumps there, runs through the function, then jumps back to where it was called from at the end/return of the function.

 

Perhaps just

 

<?php 

$amount = 5;
$numbers = range( 1,100 );
shuffle( $numbers );

$lottery = array_splice( $numbers, 0, $amount );

print_r( $lottery );

?>

 

But this is not what the OP wanted.

 

The answer is yes. Why not try it out rather than asking?

Thanks for that, one extra thing is how can i send a variable made inside the executed function back to the parent function loop without resetting the while loop?

 

While technically possible, you would nee to be very, very careful.

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.