Dynamic variables on loop

Discussion in 'PHP' started by KingCobra, Jan 1, 2010.

  1. #1
    Refer to the snippet below:

    $i=0;
    for($i=0;$i<=$n;$i++){
    $var.$i=$_POST["query".$i];
    }


    I just need to generate variables out of the loop. e.g. $var1,$var2,$var3...

    I will store some data on that variables for later printing.

    I've tried the snippet using the format above but it never worked. Any solution for this?

    * the loop maybe for or while
     
    KingCobra, Jan 1, 2010 IP
  2. KingCobra

    KingCobra Well-Known Member

    Messages:
    289
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    103
    #2
    Problem SOLVED


    But you can post your technic for me, for more learning. Thanks
     
    KingCobra, Jan 1, 2010 IP
  3. CodedCaffeine

    CodedCaffeine Peon

    Messages:
    130
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #3
    <?php
    # Some defined constant.
    $n = 4;
    
    # Loop until $i = 4
    for($i=0;$i<=$n-1;$i++)
    {
    	# Set the variable name.
    	$var = 'var'.(string)$i;
    	
    	# Set the POST field to be a 'variable variable';
    	$$var = $_POST["query".$i];
    }
    
    # Now, the data can be retrieved with 'var'.$i;
    echo $var0; // REMEMBER! STARTS AT ZERO because of $i.
    echo $var1;
    echo $var2;
    echo $var3;
    Code (markup):
     
    Last edited: Jan 2, 2010
    CodedCaffeine, Jan 2, 2010 IP
  4. markowe

    markowe Well-Known Member

    Messages:
    1,136
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    165
    #4
    Eugh, is there any reason why you're not using an array for this? Like this:

    
    $var[] = $_POST["query".$i];
    
    Code (markup):
    That will push each POST item onto the array, so you will get:

    $var[0] = postitem1
    $var[1] = postitem2

    etc.

    That would be the way to do it in 99% of situations, that's what arrays are for!
     
    markowe, Jan 2, 2010 IP