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 Quote Link to comment 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? Quote Link to comment 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 Quote Link to comment 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) Quote Link to comment Share on other sites More sharing options...
plznty Posted October 29, 2010 Author Share Posted October 29, 2010 Thank you! Quote Link to comment 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 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.