variable names inside a for -loop

Discussion in 'PHP' started by tikitin, Sep 12, 2007.

  1. #1
    I am sending a bunch of variables from Flash to be inserted into a mysql database. The names of variables are like:
    $varA_0, $varA_1, $varA_2, $varB_0, $varB_1, $varB_2, etc
    Some of the variables hold a string, some hold an integer.

    My problem is that I can't figure out how to write the variable names inside a for -loop.

    This definitely does not work:
    for ($i;$i<3;$i++){
    mysql_query("insert into dbTable values($varA_$i,$varB_$i)");
    }

    Whatever way I write the variable names, all I am getting are the values of $i. I suppose this is once more a case of placing the quotation marks correctly?

    Another thing:
    Is there a limit to how many variables you can send (or receive) using GetURL from Flash?
     
    tikitin, Sep 12, 2007 IP
  2. tripy

    tripy Guest

    Messages:
    32
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    It's very simple acutally.
    You create a variable that will hold the string of the name of the variable you want, and you use it with $$

    
    $var1="a";
    $var2="b";
    $var3="c";
    for($i=1;$i<=3;$i++){
      $tmp="var$i";
      echo "value of $tmp :> $$tmp<br/>";
    }
    
    PHP:
     
    tripy, Sep 12, 2007 IP
    webrickco likes this.
  3. webrickco

    webrickco Active Member

    Messages:
    268
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    60
    #3
    Simple and effective answer, PHP like Javascript has the ability to variable the name of its own variables simply by adding another $ before the first.
     
    webrickco, Sep 12, 2007 IP
  4. hemlata

    hemlata Peon

    Messages:
    18
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Hi,
    One more solution could be to collect all the variables in an array and then use loop on it... Like..

    $values = array($varA_0, $varA_1, $varA_2, $varB_0, $varB_1, $varB_2);
    foreach ($values as $value)
    {
    // Get the varible name here as '$value' and perform the required operation
    }
     
    hemlata, Sep 12, 2007 IP