plznty Posted October 28, 2010 Share Posted October 28, 2010 currently using function gen_chars($length = 6) { // Available characters $chars = '0123456789abcdefghjkmnoprstvwxyz'; $Code = ''; // Generate code for ($i = 0; $i < $length; ++$i) { $Code .= substr($chars, (((int) mt_rand(0,strlen($chars))) - 1),1); } return $Code; } // Usage $var = gen_chars(12); echo $var; However ide like to know if theres a more efficient way of generating this since this is going to be using a lot. Thanks Link to comment https://forums.phpfreaks.com/topic/217153-most-efficient-random-string-method/ Share on other sites More sharing options...
BlueSkyIS Posted October 28, 2010 Share Posted October 28, 2010 mt_rand generates an integer. is it helpful to put (int) in front of it? Link to comment https://forums.phpfreaks.com/topic/217153-most-efficient-random-string-method/#findComment-1127792 Share on other sites More sharing options...
plznty Posted October 28, 2010 Author Share Posted October 28, 2010 nah i just need random letters/numerals generated. ty Link to comment https://forums.phpfreaks.com/topic/217153-most-efficient-random-string-method/#findComment-1127805 Share on other sites More sharing options...
mikecampbell Posted October 29, 2010 Share Posted October 29, 2010 In my test this was about 15% faster then your original - it eliminates a bunch of calls to strlen. function gen_chars($length = 6) { // Available characters $chars = '0123456789abcdefghjkmnoprstvwxyz'; $len = strlen($chars); $Code = ''; // Generate code for ($i = 0; $i < $length; ++$i) { $Code .= substr($chars, ((mt_rand(0,$len)) - 1),1); } return $Code; } However, this was about twice as fast (for whatever reason)! function gen_chars($length = 6) { // Available characters $chars = '0123456789abcdefghjkmnoprstvwxyz'; $charsarray = str_split($chars); $len = strlen($chars)-1; $Code = ''; // Generate code for ($i = 0; $i < $length; ++$i) { $Code .= $charsarray[(mt_rand(0,$len))]; } } Of course, I tested building a string 500,000 characters long, so if you are only building short strings then yours will be faster! (less overhead) Link to comment https://forums.phpfreaks.com/topic/217153-most-efficient-random-string-method/#findComment-1127807 Share on other sites More sharing options...
plznty Posted October 29, 2010 Author Share Posted October 29, 2010 Thank you! Link to comment https://forums.phpfreaks.com/topic/217153-most-efficient-random-string-method/#findComment-1127809 Share on other sites More sharing options...
sharal Posted October 29, 2010 Share Posted October 29, 2010 Or simply: $myvalue = uniqid(); echo $myvalue; http://dk.php.net/manual/en/function.uniqid.php Link to comment https://forums.phpfreaks.com/topic/217153-most-efficient-random-string-method/#findComment-1127911 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.