Jump to content

how to assign variable to items in an array?


BigTime

Recommended Posts

Running a simple query:

 

SELECT team, rank from table ORDER BY rank ASC

 

returns 8 records in order from 1 to 8

 

I then want to a assign a new variable to each that I can use for later queries ie:

 

team with rank 1 = $team1

team with rank 2 = $team2

team with rank 3 = $team3

 

etc....

 

 

Thanks in advance.

I'm not really sure if I know what you mean, but it sounds like you're looking for a way to use a variable's value as another variable's name... So you can dinamically create the variables names... check out http://php.net/manual/en/language.variables.variable.php.

 

here's an example:

 

<?php
// create the name you wish to use as a variable
$VariableName = "rank"."1";
// Assign a value (team name) to the new variable
$$VariableName = "teamName";
// echo results
echo $rank1;
?>

 

Hope this helps

thank you both for the help.  Im now able to reference and echo $team1 through $team8 throughout my document.

 

Can anyone please point me to more information on $$VariableName?  why the two $$?

 

My final code that worked:

    # setup SQL statement
    $SQL = " SELECT DISTINCT team, rank FROM table ORDER BY by rank ASC";
    # execute SQL statement
    $teamsquery = mysql_db_query($db, $SQL, $cid);
    # check for errors
    if (!$teamsquery) { echo( mysql_error()); }

while($row=mysql_fetch_array($teamsquery)) {
$team=$row["team"];
$rank=$row["rank"];

// create the name you wish to use as a variable
$VariableName = "team"."$rank";
// Assign a value (team name) to the new variable
$$VariableName = "$team";
}

 

 

I know you want to use variables but arrays are the right way to do this. First team is $team[1], second is $team[2], and so on.

    $teams = array();
    # setup SQL statement
    $SQL = " SELECT DISTINCT team, rank FROM table ORDER BY by rank ASC";
    # execute SQL statement
    $teamsquery = mysql_db_query($db, $SQL, $cid);
    # check for errors
    if (!$teamsquery) { echo( mysql_error()); }

while($row=mysql_fetch_array($teamsquery)) {
// Append a value (team name) into the array
$teams[$row["rank"]] = $row["team"];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.