I have a Function to generate random string ,it produce more than 1 random string ,but how to separate them
Function generatorstring($count) {
$karakter = '0123456789abcdefghijklmnopqrstuvwxyz';
$length = 7;
$randomString = '';
for ($i=0; $i <$count ; $i++) {
for ($ia = 0; $ia < $length; $ia++) {
$randomString .= $karakter[rand(0, strlen($karakter) - 1)];
}
}
return $randomString ;
}
echo generatorstring(3);
I expected result like this
'As6s8Xs',
'zE71jnM',
'ak9a71b',
But, its only produce 1 line of random string.
Well, right off the bat, your biggest problem is that you have a for loop using a variable that is inside a for loop using the same variable.
First for loop establishes $i as 0, incrementing 1. Second for loop (inside) overwrites $i as 0 and increments until $i equals $length. $i is now 7. Outer for loop sees $i is 7, which is greater than $count (3), therefore the outer for loop breaks.
for($i=0; $i < $count; $i++) {
for($ia=0; $ia < $length; $ia++){
//do something
}
}
Also note, this is ugly, and it is better, as @dWinder mentioned, to put your inner for loop in its own function.
You should separate your code for function creating random string and then call it 3 times.
Separating code to small function doing simple action is basic for good practice programming.
Consider:
function generatorstring($length = 7){
$karakter = '0123456789abcdefghijklmnopqrstuvwxyz';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $karakter[rand(0, strlen($karakter) - 1)];
}
return $randomString;
}
And now just call it as:
for ($i = 0; $i < 3; $i++)
$res[] = generatorstring();
Or create a function who create array of random strings as:
function createRandomStringArray($count) {
for ($i = 0; $i < $count; $i++)
$res[] = generatorstring();
return $res;
}
And then you can print the $res
array using print_r
or another loop