Notice: Uninitialized string offset in PHP

前端 未结 2 1612
予麋鹿
予麋鹿 2021-01-03 10:46

Hi I have this function and it returning a notice:

Notice: Uninitialized string offset

function generaterandomkey($length) {       

    $string=\'\'         


        
相关标签:
2条回答
  • 2021-01-03 11:02

    the best way : convert your string expression to array and then convert to string like this:

    function readnumber know a number with any length:

    function readnumber($str, $i) 
    {
        $string=$str;
        $number = '';
        $s="";
        for($j=0;$j<strlen($string);$j++)
        {
            $char=$string[$j];
            $char.=" ";
            $s.=$char;
        }
        $s=explode(" ",$s);
        while ($this->is_number($s[$i]))
            $number .= $s[$i++];        
        return $number;
    }
    

    can use it like this:

    $str="154+458-8";
    $number=readnumber($str,1);
    echo($number);
    
    0 讨论(0)
  • 2021-01-03 11:19

    You are occasionally overrunning $characters because of strlen($characters), which should be strlen($characters) - 1. Your random range should begin with zero, and you need to end with the length minus one. If the length of $characters is 10, then the last zero-based array index is nine, and that becomes your upper bound for random selection.

    $string='';
    $characters = "0123456789abcdef";
    for ($p = 0; $p < $length ; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters) - 1)]; 
    }
    

    Because you are choosing randomly, you wouldn't always receive the notice -- it would only occur if mt_rand() returned its maximum value at some point in your loop.

    0 讨论(0)
提交回复
热议问题