Populating a table with changing variables

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TheServant
    Recognized Expert Top Contributor
    • Feb 2008
    • 1168

    Populating a table with changing variables

    Hey guys,
    Basically I have a really big table with lots of variables all over the place.
    eg.
    [PHP]
    <table>
    <tr><td><?php echo( $var1." is ".$var2 ); ?></td></tr>
    <tr><td><?php echo( $bar1." is ".$bar2 ); ?></td></tr>
    <tr><td><?php echo( $dar1." is ".$dar2 ); ?></td></tr>
    <tr><td><?php echo( $sar1." is ".$sar2 ); ?></td></tr>
    ...
    [/PHP]

    Now I want to do a for loop which will make the table for me echo-ing the <td> and <tr> aswell, however I want to change the variable name, so something like making an array:
    [PHP]$array = array('var', 'bar', 'dar', 'sar');[/PHP]
    And then having a for loop with something like:
    [PHP]for ( i=0; name1=$array[i]; i++ ) {
    echo( "<tr><td>".$nam e.1." is ".$name.2." </td></tr>" );
    }[/PHP]

    Firstly, is my for loop condition correct? Regardless, my main question is the echo line: How do you add a number (or characters) to the end of a variable name to change what variable it is? Can you?
  • adamalton
    New Member
    • Feb 2007
    • 93

    #2
    There are several things that might be what you're after.

    The foreach loop. This loops through each element of an array.
    e.g.[PHP]$my_array=array ('cow','sheep', 'dog','cat');
    foreach($my_arr ay as $element){
    print "$element<b r>";
    }[/PHP]That would print out:
    cow
    sheep
    dog
    cat

    Another thing that might help you is variable variables. They are variables where the name of the variable can itself be a variable.

    I would try to explain but I think this explanation is as good as any:


    So you can do things like this:[PHP]$variable1='cow ';
    $varaible2='she ep';
    $varaible3='dog ';
    $varaible4='cat ';

    for($i=1; $<=4; $i++){
    $variable_name= 'variable' . $i;
    print $$variable_name ;
    }[/PHP]
    That's a totally useless example because you might as well have used an array, but you get the idea (I hope).

    Comment

    • TheServant
      Recognized Expert Top Contributor
      • Feb 2008
      • 1168

      #3
      Cheers mate,
      I think that is what I want. I will try it a bit later to make sure. Never used that $$variable way.

      Comment

      • ronverdonk
        Recognized Expert Specialist
        • Jul 2006
        • 4259

        #4
        Originally posted by TheServant
        Cheers mate,
        I think that is what I want. I will try it a bit later to make sure. Never used that $$variable way.
        See for the use of these type of variables also markusn00b's article in the PHP article section titled Turn array indices into variables.

        Ronald

        Comment

        Working...