View Full Version : concatenating value in a loop onto a variable

11-16-2011, 10:06 PM
Hey quick question. I want to concatenate the 5 random values of an array into a variable. Here is what i got:

$abc= array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
for ($i=0;$i>5;$i++){
$s .= $abc[rand(0,25)];}
echo $s;

So for example when i echo $s it would be 5 random letters stored in $s.

I think i know where the problem is, i think i cant say .= to add the random letter into the null variable s. How do i do this in php? I know in Javascript its += but that doesnt work either. Thanks.

11-16-2011, 10:18 PM
.= is correct.
If you try with the above (and if it were to work, which it won't but we'll get into that), you should be issued with a warning that $s has not been declared. A simple $s = ''; before the loop would work.
Your overall problem is your loop condition. It never loops since $i is never greater than 5. That should be < 5, not > 5.
An easier solution may be to shuffle an array, implode it and extract a slice.

$abc = range('a', 'z');
$s = implode('', array_slice($abc, 0, 5));

The difference between yours and mine is that mine would not allow repeatable characters, and would therefore be limited to a maximum of sizeof($abc), while yours will allow repetition and be limited to inifinity.

11-16-2011, 11:10 PM
ahh ok that makes sense thank you. i didnt even see my typo in the loop condition haha