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

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.

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;
}

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;
}

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.