-2

My code

function rand_string($length) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ]; // this line error 
 }
return $str;
}

Error

PHP Notice: Undefined variable: str in ... on line 5

2 Answers2

0

Come on, this is rather simple:

function rand_string($length) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $size = strlen( $chars );
    $str = "";
    for( $i = 0; $i < $length; $i++ )
        $str .= $chars[ rand( 0, $size - 1 ) ]; // this line now corrected
    return $str;
}
Jan
  • 42,290
  • 8
  • 54
  • 79
0

You are "adding" a string to a unknown variable $str The Line

 $str .= ....

is the culprit. .= is a string concatenation. The long form would be

$str = $str . "whatEver";

and this whats happens in the background and that 's why PHP give the Undefined Variable Notice.

To get rid of this notice you just have to declare the variable before concatenate it.

function rand_string($length) {
    $str = "";

Now the $str is known and further strings can be added.

MrMagix
  • 116
  • 1
  • 4