gtal3x Posted November 22, 2007 Share Posted November 22, 2007 It should return any random number from 0 to 10 exept the numbers that are in $used... However the script sometimes returns the numbers thats its not supost to return... any idea why? <?php $used = array("0","1","2","3","4","5","6"); $number = rand(0,10); for ($i=0;$i<=4;$i++){ while ($number == $used[$i]) { $number = rand(0,10); } } echo $number; ?> Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted November 22, 2007 Share Posted November 22, 2007 You need to use the in_array() function to determine if a particular value is in an array: <?php $used = array("0","1","2","3","4","5","6"); $number = rand(0,10); while(in_array($number,$used)){ $number = rand(0,10); } echo 'Number: '.$number; ?> Of course, the above code would enter into an infinite loop should all the possible numbers gererated by the rand() function be in the $used array. Quote Link to comment Share on other sites More sharing options...
revraz Posted November 22, 2007 Share Posted November 22, 2007 Well for one, you are not stopping the script once you found a number. You are also only going through it 4 times. Quote Link to comment Share on other sites More sharing options...
rajivgonsalves Posted November 22, 2007 Share Posted November 22, 2007 check out this post http://www.phpfreaks.com/forums/index.php/topic,167350.0.html a function I wrote following is the code <?php function urand($intMin,$intMax,$strExclude) { $arrExclude = explode(",",$strExclude); while ($intTempRand = rand($intMin,$intMax)) { if (!in_array($intTempRand,$arrExclude)) { return $intTempRand; } } } $excluding = '1,6,8,9'; $rand = urand(1,10,"$excluding"); echo $rand; ?> Quote Link to comment Share on other sites More sharing options...
trq Posted November 22, 2007 Share Posted November 22, 2007 Perfect opertunity for recursion. <?php function getrand($used) { $number = rand(0,10); if (in_array($number,$used)) { $number = getrand($used); } return $number; } echo getrand(range(0,6)); ?> Quote Link to comment Share on other sites More sharing options...
gtal3x Posted November 22, 2007 Author Share Posted November 22, 2007 Thanks a lot Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.