使用变量outside for循环语句

i want to loop a variable and assign this variable in database i use this code

$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";    
$size = strlen( $chars );
for( $i = 0; $i < 10; $i++ ) {
    $str = $chars[ rand( 0, $size - 1 ) ];
}

if i use $str outside the for loop it will give me just 1 random character if i use it indside for loop it will give me random 10 character

how can i use this code to generate the random 10 characters ??

i tried to define the variable before loop string like this

$str = '';

but also not working for me..

Every time you do $str = $chars[ rand( 0, $size - 1 ) ]; you are replacing $str's value. To append, or concatenate, all the generated characters use the . operator, like:

$str .= $chars[ rand( 0, $size - 1 ) ];

This is the same as doing the following:

$str = $str . $chars[ rand( 0, $size - 1 ) ];

Documentation: http://php.net/manual/en/language.operators.string.php

add '.' (dot) to '=' for string concatenation - it give you 10 char string

$str = '';
for( $i = 0; $i < 10; $i++ ) {
    $str .= $chars[ rand( 0, $size - 1 ) ];
}

echo $str;

or

use [] to get array of chars

for( $i = 0; $i < 10; $i++ ) {
    $str[] = $chars[ rand( 0, $size - 1 ) ];
}

print_r($str);

in php you append something to the string using the .= :

$str .= $chars[ rand( 0, $size - 1 ) ];