slpctrl Posted September 5, 2008 Share Posted September 5, 2008 How would I return any 5 random characters from a string? Let's say I've got this: <?php $str1 = md5(microtime() * mktime()); $str2 = str_shuffle($str1); $str = substr($str2,0,5); ?> line 1 gets a string of random characters line 2 shuffles those random characters line 3 gets the first 5 characters Instead of getting the first 5 characters, how can I return 5 random characters? Link to comment https://forums.phpfreaks.com/topic/122945-return-random-characters/ Share on other sites More sharing options...
fanfavorite Posted September 5, 2008 Share Posted September 5, 2008 Something like this? $chars = "abcdefghijkmnopqrstuvwxyz023456789"; srand((double)microtime()*1000000); $i = 0; $pass = '' ; while ($i <= 4) { $num = rand() % 33; $tmp = substr($chars, $num, 1); $pass = $pass . $tmp; $i++; } Link to comment https://forums.phpfreaks.com/topic/122945-return-random-characters/#findComment-634944 Share on other sites More sharing options...
BlueSkyIS Posted September 5, 2008 Share Posted September 5, 2008 you are already returning 5 random characters. str_shuffle makes the string random, then you take the first 5 characters. it literally can't get 'more random' than that. if it makes you feel better, you could use str_shuffle again, then take the first 5 characters. but since str_shuffle already randomized the first 5 chars, it's a waste of effort. grad level stats, don't you know. Link to comment https://forums.phpfreaks.com/topic/122945-return-random-characters/#findComment-634945 Share on other sites More sharing options...
Ken2k7 Posted September 5, 2008 Share Posted September 5, 2008 You can use uniqid(), but the way you have it, it's already unique even before the str_shuffle. Link to comment https://forums.phpfreaks.com/topic/122945-return-random-characters/#findComment-634948 Share on other sites More sharing options...
slpctrl Posted September 5, 2008 Author Share Posted September 5, 2008 you are already returning 5 random characters. str_shuffle makes the string random, then you take the first 5 characters. it literally can't get 'more random' than that. if it makes you feel better, you could use str_shuffle again, then take the first 5 characters. but since str_shuffle already randomized the first 5 chars, it's a waste of effort. grad level stats, don't you know. Yeah that's what I was thinking. Thanks I'm dumb Link to comment https://forums.phpfreaks.com/topic/122945-return-random-characters/#findComment-634950 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.