Eagle710 Posted February 20, 2008 Share Posted February 20, 2008 I have an array where i have placed a bunch on rand() generated numbers.. im trying to figure out a way to go through the array and check to see if there are duplicates if so i would like a number re generated. Any help? Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted February 20, 2008 Share Posted February 20, 2008 Why don't you check when putting the random number into the array? <?php $rn = array(); for ($i=0;$i<100;$i++) { $tst = rand(1,1000); while (in_array($tst,$rn)) { echo $tst . ' is already in the array<br>'; // debug -- check $tst = rand(1,1000); } $rn[$i] = $tst; } echo '<pre>' . print_r($rn,true) . '</pre>'; ?> Ken Quote Link to comment Share on other sites More sharing options...
priti Posted February 20, 2008 Share Posted February 20, 2008 Before inserting the new random number simplY check USING - in_array($arr,$new_random_num).if it return true select another random number and proceed. Regards Quote Link to comment Share on other sites More sharing options...
mainewoods Posted February 20, 2008 Share Posted February 20, 2008 php provides an array function for just that: http://www.php.net/manual/en/function.array-unique.php // one line solution $myunique = array_unique($myarray); Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted February 20, 2008 Share Posted February 20, 2008 I don't think that will work in this case, since it reduces the size of the array if there are duplicates. Ken 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.