Jump to content

Create a random string without using the same char twice


Wuhtzu

Recommended Posts

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

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"));

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.