shamuraq Posted September 3, 2009 Share Posted September 3, 2009 hi all, I've been trying to source for script to produce unique for digit number as in getting php to randomise 4 digits with no digit having same value. So i tried this code i got from http://forums.digitalpoint.com/showthread.php?t=9048 and modified it a bit into: <? error_reporting(E_ALL); ini_set('display_errors', 1); $arr = array(); $i=0; $result = array(); while ( count($arr) < 6 ) { $x = mt_rand(1,10); if ( !in_array($x,$arr) ) { $result[$i] = $x; $i+=1; } } print_r($x); ?> This is the output that i got: Fatal error: Maximum execution time of 30 seconds exceeded in D:\Apache Group\Apache2\htdocs\..... on line 11 Any suggestions? Link to comment https://forums.phpfreaks.com/topic/172933-solved-problem-using-while-to-get-unique-number/ Share on other sites More sharing options...
Garethp Posted September 3, 2009 Share Posted September 3, 2009 Change $result[$i] to $arr[$i] See, your adding to the result array, but your saying, while the arr array is less than 6 things, keep going, but your never making the arr array longer than 0 Link to comment https://forums.phpfreaks.com/topic/172933-solved-problem-using-while-to-get-unique-number/#findComment-911417 Share on other sites More sharing options...
shamuraq Posted September 3, 2009 Author Share Posted September 3, 2009 maybe its just sleepless nights trying to get this thing working... i made the change "$result[$i] to $arr[$i]" and only 1 number came out instead of 6 numbers... <? error_reporting(E_ALL); ini_set('display_errors', 1); $arr = array(); $i=0; $result = array(); while ( count($arr) < 6 ) { $x = mt_rand(1,10); if ( !in_array($x,$arr) ) { $arr[$i] = $x; $i+=1; } } print_r($x); ?> Link to comment https://forums.phpfreaks.com/topic/172933-solved-problem-using-while-to-get-unique-number/#findComment-911423 Share on other sites More sharing options...
TeNDoLLA Posted September 3, 2009 Share Posted September 3, 2009 print_r($arr); <-- holds your results. Link to comment https://forums.phpfreaks.com/topic/172933-solved-problem-using-while-to-get-unique-number/#findComment-911425 Share on other sites More sharing options...
shamuraq Posted September 3, 2009 Author Share Posted September 3, 2009 Your're sooooooooooooooo right!!!! Thanx mate!!! Link to comment https://forums.phpfreaks.com/topic/172933-solved-problem-using-while-to-get-unique-number/#findComment-911430 Share on other sites More sharing options...
thebadbad Posted September 3, 2009 Share Posted September 3, 2009 You don't have to use a loop: <?php $numbers = range(1, 10); shuffle($numbers); echo implode('', array_slice($numbers, 0, 4)); ?> Should be faster. Link to comment https://forums.phpfreaks.com/topic/172933-solved-problem-using-while-to-get-unique-number/#findComment-911433 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.