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.

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.

 

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

Two more efficient methods of getting the four values would be as follows:

 

$links = array_intersect_key($cds, array_fill_keys(array_rand($cds, 4), 0));

 

OR

 

$links = $cds;
shuffle($links);
$links = array_slice($links, 0, 4);

 

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.