Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Sep 2011
    Posts
    9
    Thanks
    3
    Thanked 0 Times in 0 Posts

    concatenating value in a loop onto a variable

    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.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    .= 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.
    PHP Code:
    $abc range('a''z');
    shuffle($abc);
    $s implode(''array_slice($abc05)); 
    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.

  • Users who have thanked Fou-Lu for this post:

    Zwake (11-16-2011)

  • #3
    New to the CF scene
    Join Date
    Sep 2011
    Posts
    9
    Thanks
    3
    Thanked 0 Times in 0 Posts
    ahh ok that makes sense thank you. i didnt even see my typo in the loop condition haha


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •