Change variable name in a for loop

Home Forums Languages PHP & MySQL Change variable name in a for loop

Tagged: 

This topic contains 1 reply, has 2 voices, and was last updated by  saaraneth 1 year, 9 months ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #13936

    Luka
    Participant

    Hey, I was trying to do something like this

    <?php
    for ($i = 1; $i <= 3; $i++) {
    $variable = $variable.$i
    }
    ?>

    Now, that doesn’t work (obviously), but what I want to get is 3 variables, variable1, variable2 and variable3, with for loop. Is it possible to do this?

    EDIT: Found it, in case anyone’s wondering:

    <?php
    for ($i = 1; $i <= 3; $i++) {
    $variable = ${'variable'.$i}
    }
    ?>

    #14797

    saaraneth
    Participant

    great that you got it working, seems like storing variables in an array would be easier, without having to concatenate strings to get a variable name:

    for($i = 0; $i<3; $i++){

    $var = $arr[$i];

    }

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.