Jump to content

Create a random string without using the same char twice


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

?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.