Jump to content

Generate Numbers from array except for the ones from another array


President Obama

Recommended Posts

$bl = array(); 
$link1 = array_rand($cds); 
$link2 = array_rand($cds); 
$link3 = array_rand($cds); 
$link4 = array_rand($cds); 
$A = 0;
while (!in_array($link1, $bl)){
$link1 = array_rand($cds);
$bl[$A] = $link1;
$A++;
}
while (!in_array($link2, $bl)){
$link2 = array_rand($cds);
$bl[$A] = $link2;
$A++;
}
while (!in_array($link3, $bl)){
$link3 = array_rand($cds);
$bl[$A] = $link3;
$A++;
}
while (!in_array($link4, $cds)){
$link4 = array_rand($cds);
$bl[$A] = $link4;
$A++;
}
echo $link1;
echo $link2;
echo $link3;
echo $link4;

 

Pretty much I'm trying to generate 4 number's between the min and max of an array but I don't want any duplicates. So it checks if the number exists in a bl array if it does it generates another number, well thats the theory. Doesn't work like that though.

Link to comment
Share on other sites

Something like this should do.

 

<?PHP

  $cds    = array('0','1','4','6','12','14','17','20');
  $result = array();

  $numberCount = 4;
  $thisCount   = 0;

  while($thisCount<$numberCount) {
    $thisNumber = array_rand($cds);
    if(!in_array($thisNumber, $result)) {
      $result[$thisCount] = $thisNumber; $thisCount++;
    }
  }

  print_r($result);
?>

 

Try the code and tell me how it goes :)

 

Regards, PaulRyan.

 

Link to comment
Share on other sites

Instead of building an inefficient while() loop, just use the function that PHP already provides! array_rand() takes a second, optional parameter for the number of random values to get.

$links = array_rand($cds, 4);

 

$links will then old the random keys that you can use to reference the values of the links

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.