PHP random charactors problem

Discussion in 'PHP' started by ReFanO, Apr 3, 2011.

  1. #1
    i created random charactors script. but got this error for some times refreshing.
    Uninitialized string offset: 61 in [COLOR="darkred"]my php file[/COLOR] on line 5
    Code (markup):
    This is code
    <?php 
    $length = 5;
        $characters = '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $string = "";    
        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[rand(0, strlen($characters))];
        }
    	echo $string;
    ?> 
    Code (markup):

     
    ReFanO, Apr 3, 2011 IP
  2. Sepehr

    Sepehr Peon

    Messages:
    568
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I think the problem is that rand can generate up to exact length of the alphabet string you have so let's say it chooses the max amount. in this case there are no 5 characters after it to choose from. so you need to change it to:
    
    rand(0, strlen($characters)-$length)
    
    PHP:
    you can also try this:
    
    <?php
    $len=5;
    $chars = '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $string=str_shuffle($chars);
    $string=substr($string, rand(0, strlen($chars)-$len), $len);
    echo $string;
    ?>
    
    PHP:
     
    Sepehr, Apr 3, 2011 IP
  3. ReFanO

    ReFanO Peon

    Messages:
    14
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks
    this code is working fine
     
    ReFanO, Apr 3, 2011 IP