cannot put variable in foreach so what to do

Discussion in 'PHP' started by mnymkr, Jun 20, 2007.

  1. #1
    I am using two foreach statements to build a table from my database

    the first one uses the keys to write the column headers

    the second one rights the values

    I want to put a variable by my key header . the variable is a dynamically generated string that recreates the GET url, so i can sort.

    i am thinking you can't put variables in foreach unless you define them in each foreach

    is this correct?

    here is what i am trying to do:

    //set up the table:
    	echo "<table border='1'><tr>";
    	//get the first row in the table:
    $row = mysql_fetch_assoc($result);
    	//print the column names as table headers:
    	foreach($rows as $key=>$value)
    	{
    		echo "<th><a href='$geturl&sort=$key&order=ASC'>UP</a>$key<a href='$geturl&sort=$key&order=DESC'>Down</a></th>";
    	}
    	echo "</tr>";
    	//loop through the table, printing
    	//the field values in table cells:
    Code (markup):
     
    mnymkr, Jun 20, 2007 IP
  2. UnrealEd

    UnrealEd Peon

    Messages:
    148
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #2
    nope:

    foreach, for, while, if and echo aren't functions, but language constructs. They don't have the same properties as functions. You can access a variable, which is declared outside your loop, inside it.

    apart from that: $_GET (and all the other $_* variables) variables are superglobal, which means you can access them anywhere in your script (in functions, classes, ...)
     
    UnrealEd, Jun 20, 2007 IP
  3. mnymkr

    mnymkr Well-Known Member

    Messages:
    2,328
    Likes Received:
    32
    Best Answers:
    0
    Trophy Points:
    120
    #3
    then how come i can access the $geturl that i have declared before the foreach statement?
     
    mnymkr, Jun 20, 2007 IP
  4. UnrealEd

    UnrealEd Peon

    Messages:
    148
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #4
    ;)
    Only when you use functions you will have to declare the value global inside each function. But as loops aren't function, you don't have to do so
     
    UnrealEd, Jun 20, 2007 IP