Wuhtzu Posted October 3, 2007 Share Posted October 3, 2007 Hey What do you guys think are the smartest / easiest / neatest way of creating a "random string" without using the same character more than once? This is what I have come up with so far: <?php $chars = array('a','b','c','d','e'); $count = count($chars); $i = 0; while($i < $count) { $rand = array_rand($chars); $string .= $chars[$rand]; unset($chars[$rand]); $i++; } echo $string; ?> But I'm not sure if I like the use of unset(). Can it be done in another way? Best regards Wuhtzu Link to comment https://forums.phpfreaks.com/topic/71712-create-a-random-string-without-using-the-same-char-twice/ Share on other sites More sharing options...
MmmVomit Posted October 3, 2007 Share Posted October 3, 2007 http://www.php.net/manual/en/function.shuffle.php Then just grab the first however-many elements you want. Link to comment https://forums.phpfreaks.com/topic/71712-create-a-random-string-without-using-the-same-char-twice/#findComment-361064 Share on other sites More sharing options...
Wuhtzu Posted October 3, 2007 Author Share Posted October 3, 2007 Smart one MmmVomit <?php $chars = array('a','b','c','d','e'); shuffle($chars); foreach($chars as $char) { $string .= $char; } echo $string; ?> Any smarter ? Link to comment https://forums.phpfreaks.com/topic/71712-create-a-random-string-without-using-the-same-char-twice/#findComment-361096 Share on other sites More sharing options...
MmmVomit Posted October 3, 2007 Share Posted October 3, 2007 This is a long shot, but a string can be treated as an array of characters. I don't have PHP on this computer, but see what happens when you feed the shuffle function a string. Try this and let me know what the output is. <?php print_r(shuffle("abcde")); ?> Link to comment https://forums.phpfreaks.com/topic/71712-create-a-random-string-without-using-the-same-char-twice/#findComment-361099 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.