Jump to content

Random String Function not working correctly!


Jragon

Recommended Posts

Hey guys,

 

I getting a problem with my ranbom string crater

 

My function:

function randstr($length){
    $characters = '0123456789QWERTYUIOPLKJHGFDSAZXCVBNM<>?:@~}{+_)(*&^%\$£!¬`-=[\'],./¦';
    $string ='';


    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}

 

What happens:

when i spefafi the length it dosent allwas keep to that length(the length is 55 chariters)

 

Also what i want it to do is only have 1 of each chariters.

 

Thanks

 

Jragon

Link to comment
Share on other sites

function randstr($length) {
    $characters = '0123456789QWERTYUIOPLKJHGFDSAZXCVBNM<>?:@~}{+_)(*&^%\$£!¬`-=[\'],./¦';
    $characters = join($characters);
    $string = ""; 

    while (strlen($string) < $length) {
          $string .= $characters[array_rand($characters, 1)];
    }

    return $string;
}

 

Not really sure why your way was not working, but the above should work.

Link to comment
Share on other sites

I'll look at this later as it can probably be simplified, but for now:

 

function randstr($length) {
    $characters = str_split('0123456789QWERTYUIOPLKJHGFDSAZXCVBNM<>?:@~}{+_)(*&^%\$£!¬`-=[\'],./|');
    $string = implode(array_intersect_key($characters, array_flip(array_rand($characters, $length))));

    return $string;
}

Link to comment
Share on other sites

Simplified somewhat, but you need a condition in there in case the $length is 0 or greater than the number of characters.  I'm not sure what you want there (return false, return a string with a maximum length of the characters, etc.):

 

function randstr($length) {
    $characters = '0123456789QWERTYUIOPLKJHGFDSAZXCVBNM<>?:@~}{+_)(*&^%\$£!¬`-=[\'],./|';
    $string = implode(array_rand(array_flip(str_split($characters)), $length));

    return $string;
}

Link to comment
Share on other sites

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.