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? Link to comment https://forums.phpfreaks.com/topic/92032-random-in-array/ 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 Link to comment https://forums.phpfreaks.com/topic/92032-random-in-array/#findComment-471339 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 Link to comment https://forums.phpfreaks.com/topic/92032-random-in-array/#findComment-471341 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); Link to comment https://forums.phpfreaks.com/topic/92032-random-in-array/#findComment-471368 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 Link to comment https://forums.phpfreaks.com/topic/92032-random-in-array/#findComment-471550 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.